Promises & async/await
From callbacks to promises to async/await — promise states, chaining, error handling, Promise.all/allSettled/race/any, running work in parallel vs sequence, cancellation with AbortController, and common mistakes.
Asynchronous JavaScript evolved in three steps: callbacks → promises → async/await. Async/await is what you write today, but it's built entirely on promises, so you need to understand both.
Callbacks and their problems
getUser(id, (err, user) => {
if (err) return handle(err);
getOrders(user, (err, orders) => {
if (err) return handle(err);
getInvoice(orders[0], (err, invoice) => { // "callback hell" / pyramid of doom
if (err) return handle(err);
render(invoice);
});
});
});Beyond the nesting, callbacks have inversion of control problems: a third-party function might call your callback twice, never, or synchronously sometimes and asynchronously other times. Errors must be checked manually at every level.
Promises
A promise is an object representing a value that will be available later. It's in one of three states:
Once settled (fulfilled or rejected), a promise never changes. Callbacks attached with .then always run asynchronously (as microtasks — see The event loop), even if the promise is already settled.
// Creating a promise (mostly for wrapping callback APIs)
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function readFileAsync(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, "utf8", (err, data) => (err ? reject(err) : resolve(data)));
});
}
// Node has this built in: import { readFile } from "node:fs/promises"Chaining
.then returns a new promise, resolved with whatever the callback returns. Returning a promise from .then makes the chain wait for it — this flattens the pyramid:
getUser(id)
.then((user) => getOrders(user)) // returns a promise: chain waits
.then((orders) => getInvoice(orders[0]))
.then((invoice) => render(invoice))
.catch((err) => handle(err)) // catches a rejection from ANY step above
.finally(() => hideSpinner()); // runs either wayasync/await
async functions always return a promise. Inside them, await pauses the function until a promise settles, then resumes with its value — or throws its rejection reason.
async function showInvoice(id) {
try {
const user = await getUser(id);
const orders = await getOrders(user);
const invoice = await getInvoice(orders[0]);
render(invoice);
} catch (err) {
handle(err); // ordinary try/catch for async errors
} finally {
hideSpinner();
}
}Under the hood, an async function is a state machine: each await suspends it, and the continuation is scheduled as a microtask when the awaited promise settles. The thread is free to do other work meanwhile.
Sequential vs parallel
The most common performance mistake: awaiting independent operations one after another.
// Sequential: ~300 ms total if each takes 100 ms
const user = await fetchUser(id);
const posts = await fetchPosts(id);
const friends = await fetchFriends(id);
// Parallel: ~100 ms total — start all, then wait for all
const [user2, posts2, friends2] = await Promise.all([
fetchUser(id),
fetchPosts(id),
fetchFriends(id),
]);Await sequentially only when a step depends on the previous result.
Loops
// Sequential (sometimes intended: rate limits, ordering)
for (const id of ids) {
await process(id);
}
// Parallel
await Promise.all(ids.map((id) => process(id)));
// forEach does NOT wait for async callbacks — a classic bug
ids.forEach(async (id) => { await process(id); });
console.log("done?"); // runs immediately, before any processing finishesFor thousands of items, unbounded Promise.all may overwhelm a server — limit concurrency (a small pool helper, or p-limit).
The combinators
| Combinator | Settles when | Result | Use |
|---|---|---|---|
Promise.all(ps) | All fulfil, or any rejects (fail fast) | Array of values | Independent tasks that all must succeed |
Promise.allSettled(ps) | All settle | [{status, value | reason}] | Best-effort batch; report each outcome |
Promise.race(ps) | The first settles (either way) | That value/reason | Timeouts |
Promise.any(ps) | The first fulfils; rejects only if all reject | First value / AggregateError | Fastest of several mirrors |
// Timeout with race
const withTimeout = (p, ms) =>
Promise.race([p, new Promise((_, rej) => setTimeout(() => rej(new Error("timeout")), ms))]);
const results = await Promise.allSettled(urls.map((u) => fetch(u)));
const failed = results.filter((r) => r.status === "rejected");Note: Promise.all failing fast does not cancel the other operations — they keep running.
Cancellation with AbortController
Promises can't be cancelled by themselves. The standard mechanism is an AbortSignal passed into cancellable APIs:
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
try {
const res = await fetch("/api/report", { signal: controller.signal });
const data = await res.json();
} catch (err) {
if (err.name === "AbortError") console.log("cancelled");
else throw err;
} finally {
clearTimeout(timer);
}
// Shorthand: fetch(url, { signal: AbortSignal.timeout(5000) })
// Combine: AbortSignal.any([userCancelSignal, AbortSignal.timeout(5000)])In React effects, abort in the cleanup function so stale requests don't update state after unmount.
Error handling pitfalls
// 1. Forgetting to await: the error escapes try/catch
try {
saveUser(user); // no await → rejection is unhandled
} catch (e) { /* never runs */ }
// 2. Floating promises: unhandled rejections crash Node (since v15) and log errors in browsers
doSomethingAsync(); // add await, .catch(), or void it deliberately
// 3. Returning vs awaiting inside try
async function f() {
try {
return await risky(); // 'await' needed here for the catch to see the rejection
} catch { return fallback; }
}
// 4. Mixing styles confusingly
const data = await fetch(url).then((r) => r.json()); // fine, but pick one style per functionGlobal safety nets: window.addEventListener("unhandledrejection", ...) and process.on("unhandledRejection", ...) — for logging, not as a substitute for handling.
Async iteration
for await (const chunk of stream) process(chunk); // Node streams, ReadableStream
async function* paginate(url) {
while (url) {
const res = await fetch(url).then((r) => r.json());
yield* res.items;
url = res.next;
}
}
for await (const item of paginate("/api/items")) console.log(item);- A promise is pending, then fulfilled or rejected — once; then-callbacks always run asynchronously.
- then returns a new promise; returning a promise flattens chains; one catch handles the whole chain.
- async/await is syntax over promises; use try/catch for errors.
- Start independent work together and await Promise.all; never use forEach with async callbacks.
- all (fail fast), allSettled (every outcome), race (first settled), any (first success).
- Cancel with AbortController; always await or handle promises.
QPromise.all vs Promise.allSettled?easy
Promise.all resolves with an array of values when every promise fulfils, but rejects as soon as any one rejects (the others keep running, their results ignored). Promise.allSettled waits for every promise and resolves with an array describing each outcome (fulfilled with value, or rejected with reason), never rejecting.
QImplement a function that runs async tasks with at most N in parallel.hard
Keep an index into the task list and start N worker loops. Each worker repeatedly takes the next index, awaits that task, stores the result at the same position, and stops when no tasks remain. Await Promise.all over the workers, then return the results array. This preserves order and never has more than N tasks in flight.