Promises
Learn JavaScript promises, including pending, fulfilled, and rejected states, then, catch, finally, Promise.all, allSettled, any, race, and withResolvers.
On this page
1. What are promises?
When you start an async job, like fetching data from a server, you do not get the result right away. A promise is like a receipt: empty for now, and later filled with a value or an error.
Every promise is in one of three states: pending, fulfilled, or rejected. Once it settles, its state never changes again.
2. Why does it matter?
With Callbacks, nesting keeps growing and errors must be handled separately at every level. Promises give you a flat chain and error handling in one place.
| Callbacks | Promises |
|---|---|
| Every step is nested inside | A flat chain of then |
| An error check at every level | One catch handles all errors |
| Hard to combine parallel work | Promise.all and allSettled |
| A callback can run twice | A promise settles only once |
3. Where is it used?
| Place | Example |
|---|---|
| Network | fetch(url) returns a promise |
| Files (Node.js) | Methods from fs/promises |
| Parallel requests | Promise.all([getUser(), getPosts()]) |
| Timeouts | Giving up on a slow request with Promise.race |
| async / await | await works on promises |
4. How does it work?
| Method | When it runs |
|---|---|
.then(fn) | When fulfilled, with the value |
.catch(fn) | When rejected, with the error |
.finally(fn) | In both cases, for cleanup |
5. Code example
Creating a promise and chaining
function getUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: "Sara" });
else reject(new Error("User not found"));
}, 300);
});
}
getUser(1)
.then((user) => user.name.toUpperCase())
.then((name) => console.log(name))
.catch((error) => console.error(error.message))
.finally(() => console.log("Done"));Combinators
const tasks = [getUser(1), getUser(-1), getUser(2)];
const all = await Promise.allSettled(tasks);
all.forEach((r) => console.log(r.status));
const first = await Promise.any(tasks);
console.log(first.name);Promise.withResolvers
const { promise, resolve } = Promise.withResolvers();
button.addEventListener("click", () => resolve("clicked"), { once: true });
console.log(await promise);How does the code work?
| Part | Meaning |
|---|---|
Promise.all | An array if all are fulfilled, rejects immediately if even one rejects |
Promise.allSettled | Waits for all, gives each one's status and value or reason |
Promise.any | The first fulfilled, AggregateError if all fail |
Promise.race | Whichever settles first, success or failure |
Promise.withResolvers() | The promise and its resolve, reject in separate variables |
Interview tip
all vs allSettled is often asked. Use allSettled when you want every result even if some fail. Use all when one failure makes everything useless.
6. Common mistakes
Mistake: Forgetting return inside then
Why? The next then gets undefined and the chain breaks.
Better: Return a value or a promise from every then.
Mistake: Not adding a catch
Why? An unhandled promise rejection shows an error in the console and can stop the Node.js process.
Better: Add a catch at the end of every chain, or keep await inside try catch.
Mistake: Nesting promises inside then
Why? It brings callback hell back.
Better: Return the inner promise so the chain stays flat.
Mistake: Running independent requests one after another
Why? Three requests of 1 second each take 3 seconds.
Better: Run them in parallel with Promise.all, and the total time is the slowest request.
7. What to learn before and after
| Stage | Topics |
|---|---|
| Before | Callbacks, Event Loop, Timers |
| After | Async / Await, Fetch API, Error Handling |
Final quick revision
| Point | Detail |
|---|---|
| States | pending, fulfilled, rejected |
then / catch / finally | Result, error, cleanup |
| Chain | Every then gives a new promise |
all / allSettled | All together, fail fast vs a report on all |
any / race | First success vs first to settle |
withResolvers | For resolving from outside |