Promises
A promise stands for a value that will exist later: it can be pending, fulfilled or rejected.
In this page:
Syntax
promise
.then((result) => {
// success
})
.catch((err) => {
// failure
})
.finally(() => {
// always runs
});
Promises
A promise's then handles success, catch handles failure and finally runs either way. Handlers return new promises so you can chain them. Creating promises with new Promise wraps callback APIs.
Note:
Always end chains with a catch so rejections are not unhandled.
Example: Promises
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve(21), 5);
});
p.then((n) => n * 2)
.then((n) => { console.log("result:", n); throw new Error("oops"); })
.catch((e) => console.log("caught:", e.message))
.finally(() => console.log("cleanup"));
// Output:
// result: 42
// caught: oops
// cleanup
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting to return inside then
- Leaving rejections unhandled
- Creating a promise inside a promise unnecessarily
Chapter Summary
- States: pending, fulfilled, rejected
- then, catch and finally handle results
- Chains return new promises
- Always add catch
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: