Promises
A promise is an object that stands for a value you don't have yet: an API reply, a file, a payment confirmation. Instead of passing callbacks into a function, the function hands you a promise, and you attach what should happen when it succeeds or fails. Promises are the foundation of fetch and async/await.
The three states
A promise is always in one of three states:
- pending: the work is still going on;
- fulfilled: it finished successfully and has a value;
- rejected: it failed and has a reason (usually an
Error).
Once a promise is fulfilled or rejected it is settled, and it never changes again.
then handles the value, catch handles the error and finally runs after either.Creating a promise
You create one with new Promise(executor). The executor function receives two functions: call resolve(value) on success or reject(error) on failure. Here we pretend to check an M-Pesa balance, using setTimeout to simulate the network delay:
function checkBalance(amount) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (amount <= 500) {
resolve(`Approved: KES ${amount}`);
} else {
reject(new Error("Insufficient balance"));
}
}, 1000);
});
}
checkBalance(300)
.then((message) => console.log(message))
.catch((error) => console.log(error.message))
.finally(() => console.log("Done"));
checkBalance(800)
.then((message) => console.log(message))
.catch((error) => console.log(error.message))
.finally(() => console.log("Done"));
After one second, the first timer resolves its promise, and all of that promise's callbacks run as microtasks before the second timer fires. Most of the time you won't create promises yourself; you will consume promises returned by functions like fetch. Still, building one shows what is happening inside.
then, catch and finally
.then(onFulfilled)runs with the value when the promise fulfils..catch(onRejected)runs with the reason when it rejects..finally(onSettled)runs either way, with no argument. It is ideal for clean-up such as hiding a loading spinner.
Each of these returns a new promise, which is what makes chaining possible.
Chaining
Whatever a .then callback returns becomes the value for the next .then. If it returns another promise, the chain waits for that promise first. This turns nested callbacks into a flat, readable sequence.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); Promise.resolve(2) .then((n) => n * 10) // 20 .then((n) => wait(500).then(() => n + 5)) // waits, then 25 .then((n) => console.log(n));
If any step throws an error or returns a rejected promise, the chain skips the remaining .then callbacks and jumps to the nearest .catch:
Promise.resolve("42")
.then((text) => JSON.parse(text))
.then((n) => {
throw new Error(`Bad value ${n}`);
})
.then(() => console.log("never runs"))
.catch((error) => console.log("Caught:", error.message));
Forgetting to return inside a .then that uses curly braces. .then((n) => { wait(500); n + 5; }) returns undefined, so the next step receives undefined immediately without waiting. Arrow functions without braces return automatically; with braces you must write return.
Running promises together
To wait for several independent jobs at once, use the built-in combinators. These examples use two helpers:
const after = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms)); const failAfter = (ms, message) => new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
Promise.all waits for all of them and gives an array of values in the original order, no matter which finished first:
Promise.all([after(300, "rice"), after(100, "beans")]) .then((values) => console.log(values));
But if any one rejects, Promise.all rejects straight away with that error:
Promise.all([after(300, "rice"), failAfter(100, "No beans")])
.then((values) => console.log(values))
.catch((error) => console.log("Failed:", error.message));
Promise.allSettled never rejects. It waits for every promise and reports each outcome:
Promise.allSettled([after(100, "rice"), failAfter(200, "No beans")]) .then((results) => results.forEach((r) => console.log(r.status, r.value ?? r.reason.message)));
Promise.race settles as soon as the first promise settles, which is handy for timeouts. Promise.any waits for the first one to fulfil, ignoring failures unless all fail.
Promise.race([after(300, "slow matatu"), after(100, "fast boda")]) .then((winner) => console.log(winner));
| Method | Fulfils when | Rejects when |
|---|---|---|
Promise.all | all fulfil (array of values) | any one rejects |
Promise.allSettled | all settle (array of results) | never |
Promise.race | the first to settle fulfils | the first to settle rejects |
Promise.any | the first one fulfils | all reject |
Always end a chain with .catch (or use try/catch with await). A rejected promise with no handler produces an "Uncaught (in promise)" error in the console, and your user sees nothing helpful.
Key points
- A promise is pending, then settles once as fulfilled (with a value) or rejected (with a reason).
.then,.catchand.finallyeach return a new promise, so you can chain them.- Return values flow down the chain; a thrown error jumps to the next
.catch. - Use
Promise.allfor "all must succeed",allSettledfor "tell me every result" andrace/anyfor "first one wins".
Tip: use the ← and → keys to move between pages.
