Lesson 69 of 296
Promises
What you will learn
- What a promise is
- The three states of a promise
- Creating a promise
- Using
then,catchandfinally - Chaining promises
- How errors travel through a chain
- Common promise mistakes
On this page
What is a promise?
A promise is an object that represents a value that is not available yet but will be in the future, or an error if the work fails. Instead of passing a callback into a function, the function returns a promise, and you attach what should happen next.
fetch("/api/user") returns a promise straight awayThe three states
| State | Meaning |
|---|---|
| Pending | The work is still happening |
| Fulfilled | The work succeeded; the promise has a value |
| Rejected | The work failed; the promise has a reason (usually an Error) |
A promise that is fulfilled or rejected is called settled. Once settled, it never changes again.
Creating a promise
Usually libraries and built-in functions create promises for you. But you should know how:
function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
wait(1000).then(() => console.log("1 second passed"));With success and failure:
function getUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id === 1) {
resolve({ id: 1, name: "Sam" });
} else {
reject(new Error("User not found"));
}
}, 500);
});
}- The function passed to
new Promiseis called the executor. It runs immediately, synchronously. - Call
resolve(value)to fulfil,reject(error)to reject. - Only the first call counts; later calls are ignored.
- If the executor throws an error, the promise is rejected.
then, catch and finally
getUser(1)
.then((user) => {
console.log(user.name);
})
.catch((error) => {
console.error(error.message);
})
.finally(() => {
console.log("Finished");
});| Method | Runs when |
|---|---|
then(fn) | The promise is fulfilled; fn gets the value |
catch(fn) | The promise is rejected; fn gets the error |
finally(fn) | Either way. Good for cleanup, such as hiding a loading spinner. It gets no value. |
Chaining
then always returns a new promise. That new promise is resolved with whatever your callback returns. This allows a flat chain instead of nested callbacks.
getUser(1)
.then((user) => getOrders(user.id))
.then((orders) => getOrderDetails(orders[0].id))
.then((details) => console.log(details))
.catch((error) => console.error(error));Compare with the callback hell in Lesson 67.
Rules for what a then callback returns:
| The callback returns | The next then receives |
|---|---|
| A normal value | That value |
| A promise | The result of that promise, after it settles |
| Nothing | undefined |
| It throws an error | The chain is rejected; skips to the next catch |
How errors travel
An error anywhere in the chain skips all following thens and goes to the nearest catch. One catch at the end handles errors from every step.
After a catch handles an error, the chain continues as fulfilled:
Promise.reject(new Error("x"))
.catch(() => "recovered")
.then((v) => console.log(v)); "recovered"Ready-made promises
Promise.resolve(42) already fulfilled with 42
Promise.reject(new Error("failed")) already rejectedfetch: a real example
fetch("https://api.example.com/users/1")
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
})
.then((user) => console.log(user.name))
.catch((error) => console.error("Request failed:", error.message));Important: fetch only rejects on network failure. A 404 or 500 response is still fulfilled. You must check response.ok yourself. This is a very common interview question.
response.json() also returns a promise, so it is returned and the next then gets the data.
Unhandled rejections
If a promise is rejected and nothing catches it, you get an unhandled promise rejection warning in the browser. In Node.js, an unhandled rejection crashes the process by default (Node.js 15 and later). Always end chains with catch, or use try...catch with await.
Common mistakes
- Forgetting to return inside
then:
.then((user) => { getOrders(user.id); }) next then gets undefined
.then((user) => getOrders(user.id)) correct- Nesting
theninsidethen(promise hell) instead of returning and chaining. - No
catchat the end. - Thinking
fetchrejects on 404. - Wrapping a promise in
new Promisefor no reason (the "explicit construction anti-pattern"). If you already have a promise, just return it.
How to say it in an interview
"A promise represents the eventual result of an async operation and is pending, fulfilled or rejected; once settled it never changes. then returns a new promise resolved with whatever the callback returns, and if it returns a promise, the chain waits for it, which lets me write flat chains. Errors skip to the nearest catch, and finally runs either way for cleanup. fetch only rejects on network errors, so I check response.ok. Unhandled rejections crash Node.js, so every chain needs error handling."
Key words
| Word | Meaning |
|---|---|
| Promise | An object for a future value or error |
| Pending | Not finished yet |
| Fulfilled | Finished successfully with a value |
| Rejected | Failed with a reason |
| Settled | Fulfilled or rejected |
| Executor | The function passed to new Promise |
| Chaining | Connecting .then calls one after another |
| Unhandled rejection | A rejected promise that nothing catches |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.