JavaScript Promises
A Promise is an object representing a value that isn't available yet but will be at some point — or an error explaining why it never will be. Instead of passing callbacks into an asynchronous function, the function returns a promise, and you attach handlers to it.
Promise states
A promise is always in one of three states:
| State | Meaning |
|---|---|
| pending | the operation is still running |
| fulfilled | it finished successfully with a value |
| rejected | it failed with a reason (usually an Error) |
Once fulfilled or rejected, a promise is settled and never changes again.
Creating a promise
The Promise constructor receives an executor function with two parameters: resolve (call it with the result) and reject (call it with an error):
function wait(ms, value) {
return new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
}
function checkAge(age) {
return new Promise((resolve, reject) => {
if (age >= 18) resolve("access granted");
else reject(new Error("too young"));
});
}
wait(100, "tea is ready").then((msg) => console.log(msg));
checkAge(21).then((msg) => console.log("21:", msg));
checkAge(15)
.then((msg) => console.log("15:", msg))
.catch((err) => console.log("15:", err.message));21: access granted
15: too young
tea is ready
The two checkAge results print first: they settle immediately, while the wait promise takes 100 ms.
then, catch, finally
.then(onFulfilled)runs when the promise fulfils, receiving the value..catch(onRejected)runs when it rejects, receiving the error..finally(fn)runs either way — good for clean-up.
Each of these returns a new promise, so they can be chained. A value returned from a then handler is passed to the next then; returning a promise makes the chain wait for it:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function fetchUser(id) {
return wait(30).then(() => ({ id, name: "Mina" }));
}
function fetchOrders(user) {
return wait(30).then(() => [`order-1 for ${user.name}`, `order-2 for ${user.name}`]);
}
fetchUser(1)
.then((user) => {
console.log("user:", user.name);
return fetchOrders(user); // the chain waits for this promise
})
.then((orders) => {
console.log("orders:", orders.length);
return orders[0].toUpperCase();
})
.then((first) => console.log("first:", first))
.catch((err) => console.log("failed:", err.message))
.finally(() => console.log("done"));user: Mina
orders: 2
first: ORDER-1 FOR MINA
done
Compare this flat chain with the nested "callback hell" from the previous chapter.
Error handling
A rejection — or an exception thrown inside any then handler — skips the following thens and jumps to the next catch. One catch at the end handles errors from every step:
Promise.resolve(10)
.then((n) => n * 2)
.then((n) => {
if (n > 15) throw new Error(`${n} is too big`);
return n;
})
.then((n) => console.log("never runs", n))
.catch((err) => {
console.log("caught:", err.message);
return 0; // recover with a fallback value
})
.then((n) => console.log("continuing with", n));caught: 20 is too big
continuing with 0
Promise.resolve(value) and Promise.reject(error) create already-settled promises — handy for tests and for starting chains.
Running promises in parallel
When tasks don't depend on each other, start them all at once and combine their promises:
| Method | Fulfils when | Rejects when |
|---|---|---|
Promise.all(list) |
all fulfil (array of values, in order) | any rejects |
Promise.allSettled(list) |
all have settled (array of {status, value/reason}) |
never |
Promise.race(list) |
the first settles (either way) | the first settles with a rejection |
Promise.any(list) |
the first fulfils | all reject |
const delay = (ms, value, fail = false) =>
new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms)
);
Promise.all([delay(70, "A"), delay(20, "B"), delay(40, "C")])
.then((values) => console.log("all:", values));
Promise.allSettled([delay(10, "ok"), delay(45, "boom", true)])
.then((results) => console.log("allSettled:", results.map((r) => r.status)));
Promise.race([delay(90, "slow"), delay(25, "fast")])
.then((winner) => console.log("race:", winner));
Promise.all([delay(15, "fine"), delay(5, "network error", true)])
.catch((err) => console.log("all failed:", err.message));all failed: network error
race: fast
allSettled: [ 'fulfilled', 'rejected' ]
all: [ 'A', 'B', 'C' ]
Notice that Promise.all keeps the results in the order of the input, not the order they finished.
Tip: Always end a promise chain with
.catch(). An unhandled rejection is reported as an error ("Uncaught (in promise)") and can crash Node.js programs.
Test yourself
Which method runs whether a promise fulfils or rejects?
- then
- catch
- finally
- resolve
What happens when a then handler throws an error?
- The program crashes immediately
- The returned promise rejects and the next catch runs
- The error is ignored
- The next then receives the error
Promise.all rejects when…
- all promises reject
- any one promise rejects
- the slowest promise settles
- never