Lesson 26 of 50Async JavaScript
Promises
Create, chain and combine promises, handle errors in one place, and pick the right Promise combinator.
Every network request, database query and file read in modern JavaScript returns a promise. fetch, Prisma, the AWS SDK, Node's fs/promises: all of them. async/await (next lesson) is just nicer syntax on top, so when an async bug appears, like an error that vanishes or requests that run one by one when they could run together, you need to understand the promise underneath.
Before promises: callbacks
The original way to handle async work was to pass a callback that the host calls when the work is done. Node's convention put the error first: (err, result) => {}.
getUser(1, (err, user) => {
if (err) return handle(err);
getOrders(user.id, (err, orders) => {
if (err) return handle(err);
getInvoice(orders[0].id, (err, invoice) => {
if (err) return handle(err);
console.log(invoice.total);
});
});
});Each step that depends on the previous one nests one level deeper. This shape is known as callback hell (or the pyramid of doom). Error handling is repeated at every level, it is easy to forget one, and running steps in parallel and waiting for all of them needs hand-written counters.
What a promise is
A promise is an object that stands for a value that will be available later. It is always in one of three states:
- pending: the work is not finished yet.
- fulfilled: it finished successfully with a value.
- rejected: it failed with a reason (usually an
Error).
Every promise starts pending: the request is in flight, the timer is ticking.
A promise that is fulfilled or rejected is settled, and once settled it never changes again. You react to the outcome by registering handlers:
.then(onFulfilled)runs with the value..catch(onRejected)runs with the error..finally(fn)runs either way, with no argument. Good for hiding a spinner or closing a connection.
Press Run (⌘ Enter) to see what happens.Notice the last line prints first. Handlers always run asynchronously, as microtasks, even when the promise is already settled. That consistency is a feature: a then callback never runs in the middle of your current code.
resolve(5). What happens?Creating a promise
Most of the time you consume promises that libraries give you. When you need to wrap a callback API or a timer, use the Promise constructor. It takes an executor function that receives resolve and reject:
Press Run (⌘ Enter) to see what happens.The executor runs immediately and synchronously when you call new Promise. Only the handlers are deferred. If the executor throws, the promise is rejected with that error. (Top-level await, used above, is covered next lesson; for now read it as "wait for this promise".)
Chaining
.then returns a new promise, resolved with whatever your handler returns. That is what lets you chain steps in a flat line instead of nesting:
- Return a plain value: the next
.thenreceives it. - Return a promise: the chain waits for it, and the next
.thenreceives its result. - Throw: the chain skips to the next
.catch.
Press Run (⌘ Enter) to see what happens.The callback-hell example becomes four flat lines with one error handler.
What does this print?
Promise.resolve(2)
.then((x) => x * 3)
.then((x) => { x + 1; })
.then((x) => console.log(x));Error propagation
A rejection skips every .then until it reaches a .catch. After a .catch handles it, the chain continues fulfilled with whatever the catch returned. So a .catch in the middle acts like a recovery point.
What does this print?
Promise.resolve(1)
.then(() => { throw new Error("boom"); })
.then(() => console.log("skipped?"))
.catch((e) => { console.log("caught", e.message); return "fallback"; })
.then((v) => console.log("then", v));Combining promises
Often you have several independent async operations. Start them all, then combine with one of four static methods. Each takes an array of promises and returns one promise.
| Method | Fulfils when | Rejects when | Use for |
|---|---|---|---|
Promise.all | All fulfil (array of values, in input order) | Any rejects (fails fast) | Load everything a page needs; all or nothing |
Promise.allSettled | All settle, always | Never | Batch jobs where you want every result, success or failure |
Promise.race | The first to settle fulfils | The first to settle rejects | Timeouts: race the work against a timer |
Promise.any | The first to fulfil | All reject (AggregateError) | Try several mirrors, take the fastest success |
Press Run (⌘ Enter) to see what happens.Pick the combinator for each job.
Promise.all([a(), b(), c()]) take?Unhandled rejections in depth
The warning above says Node crashes on an unhandled rejection. On a real team that line decides whether one bad request takes down a server, so it is worth knowing exactly when a rejection counts as "unhandled".
The rule: after a promise is rejected, the runtime waits until the current microtasks have finished. If by then no handler is attached to that promise, it reports an unhandled rejection. It does not matter that you plan to attach one later.
That makes this innocent-looking code crash Node, even though there is a try/catch:
const sleep = (ms, value, fail) =>
new Promise((res, rej) => setTimeout(() => (fail ? rej(new Error(value)) : res(value)), ms));
const a = sleep(50, "a"); // starts now, takes 50 ms
const b = sleep(10, "b failed", true); // starts now, fails after 10 ms
try {
console.log(await a); // still waiting here when b fails
console.log(await b); // too late: nobody was listening to b at 10 ms
} catch (e) {
console.log("caught", e.message); // never runs
}
// Node: Error: b failed ... process exits with code 1Starting both requests early was a good idea. Awaiting them one at a time was not: while the code is stuck on await a, b rejects with no handler attached. The fix is to hand both to a combinator, which attaches handlers to every input immediately: const [x, y] = await Promise.all([a, b]). This is one of the most common causes of mysterious production crashes in Node services, and the forEach(async ...) bug from Async Patterns is a close cousin.
What each runtime does:
| Runtime | On an unhandled rejection | If a handler is attached later |
|---|---|---|
| Browsers | Fire unhandledrejection on window (or self in a worker), log to the console, keep running | Fire rejectionhandled |
| Node (15+) | Emit process.on("unhandledRejection"); if nothing listens, throw it as an uncaught exception and exit with code 1 | Emit rejectionHandled |
Other server runtimes are similarly strict by default; check their docs. Node's behaviour is set by the --unhandled-rejections flag. The default is throw; strict, warn and none also exist. Do not switch production servers to warn to make crashes go away. A process that keeps running after an unknown failure may be holding a broken database connection or half-written state. The usual production setup is: log the reason to your error tracker in an unhandledRejection listener, then let the process exit and have the platform (Kubernetes, systemd, your host) restart it.
process.on("unhandledRejection", (reason) => {
logger.fatal({ err: reason }, "unhandled rejection");
process.exitCode = 1;
// let in-flight work finish or time out, then exit
});const u = getUser(); const o = getOrders(); const user = await u; const orders = await o; inside a try/catch. getOrders rejects quickly while getUser is slow. What happens?Promise.withResolvers (ES2024)
The Promise constructor hands you resolve and reject only inside the executor. Sometimes the code that creates the promise is not the code that settles it: a queue that resolves a waiting consumer when an item arrives, a test that resolves a fake request on demand, a wrapper around an event that fires later. People used to write a "deferred" helper that leaked resolve out of the executor into outer variables.
Promise.withResolvers() is that helper, built in. It returns { promise, resolve, reject }. It is in all current browsers and in Node 22 and later.
Press Run (⌘ Enter) to see what happens.The same rules apply as with the constructor: settling happens once, and later calls are ignored. The danger is new, though. A promise whose resolve is stored somewhere can be forgotten, and then whoever awaits it waits forever. When you hand out resolvers, also decide what happens on timeout or shutdown: reject every waiting deferred with a clear error.
Promise.try (ES2025)
A function that "returns a promise" can still fail before it returns one, by throwing synchronously: a JSON.parse on bad input, a TypeError from a missing argument. That throw does not become a rejection. It escapes straight past your .catch.
Promise.try(fn, ...args) calls fn right away (synchronously, not on a later tick) and wraps whatever happens in a promise. A returned value fulfils it, a returned promise is followed, and a sync throw becomes a rejection. It shipped in all major browsers during late 2024 and early 2025, and is in current Node; check your targets if you support older runtimes.
Press Run (⌘ Enter) to see what happens.Before this existed, the idiom was Promise.resolve().then(fn), which also catches sync throws but delays fn to a microtask, or new Promise((resolve) => resolve(fn())). Inside an async function you rarely need any of them, because a sync throw in an async function already becomes a rejection. Promise.try earns its place in library code and plugin systems that call functions they did not write and cannot know are async.
Microtask ordering puzzles
You saw the basic ordering in The Event Loop: synchronous code, then all microtasks, then the next task. Interviews go one level deeper, into how promise chains interleave. Three rules explain every puzzle:
- Each
.thencallback is one microtask. When it finishes, the next.thenin that chain is queued at the back of the microtask queue, not run right away. - Two chains therefore take turns, one step each.
- Returning a promise (or any thenable) from a
.thencallback, or from anasyncfunction, costs two extra microtask turns before the chain moves on. The engine has to call that promise'sthenin a job of its own and then wait for it to report back.
Both Promise.resolve() are already fulfilled, so the first .then of each chain is queued: a1, then b1. The rest of each chain is not queued yet.
Press Run (⌘ Enter) to see what happens.Now the harder one, which tests rule 3:
What does this print?
Promise.resolve()
.then(() => { console.log("a1"); return Promise.resolve("x"); })
.then(() => console.log("a2"));
Promise.resolve()
.then(() => console.log("b1"))
.then(() => console.log("b2"))
.then(() => console.log("b3"))
.then(() => console.log("b4"));async functions follow the same rules. await on a native promise or a plain value costs one turn, and everything before the first await runs synchronously, as part of the caller:
Press Run (⌘ Enter) to see what happens.The output is script start, task start, script end, task after await, then, timeout. The await continuation was queued before the .then, so it runs first, and the timer waits for all microtasks.
Two honest warnings. First, the exact extra-tick counts are defined by the spec and are stable across engines today, but you should never write code that depends on them. If B must happen after A, chain it or await it. Second, in an interview, narrate the queue out loud as you go ("this queues a microtask, this goes to the task queue"). The reasoning is what is being scored, and saying it lets the interviewer give credit even if you miscount one tick.
Order the output of the task() example above.
- Tap the steps below in the right order.
sleep
Write sleep(ms) that returns a promise which resolves (with no value) after ms milliseconds. It is the building block for retries, polling and animations.
console.log("start");
await sleep(500);
console.log("half a second later");Promise.all from scratch
Write promiseAll(items) that behaves like Promise.all, without using Promise.all, allSettled, race or any:
- Returns a promise that resolves to an array of results in input order (not finish order).
- Items may be promises or plain values.
- Rejects as soon as any item rejects, with that error.
- An empty array resolves to
[]. - All items run at the same time (they were already started when you received them).
const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
await promiseAll([delay(30, "a"), "b", delay(10, "c")]); // ["a", "b", "c"]- promise
- An object representing a future value, in one of three states: pending, fulfilled or rejected.
- settled
- Fulfilled or rejected. A settled promise never changes again.
- executor
- The
(resolve, reject) => {}function passed tonew Promise. It runs immediately. - chaining
- Each
.thenreturns a new promise resolved with the handler's return value, so steps stay flat. - unhandled rejection
- A rejected promise with no handler. Logged in browsers, crashes Node by default.
- Promise.all
- Waits for every promise; resolves with all values in input order, rejects on the first failure.
- Promise.withResolvers
- ES2024. Returns
{ promise, resolve, reject }so code outside an executor can settle the promise. - Promise.try
- ES2025. Calls a function now and wraps its result, returned promise or sync throw in a promise.
- microtask
- A small job run as soon as the call stack is empty, before the next task. Promise callbacks are microtasks.