Lesson 7 of 12 · 9 min · Asynchronous JavaScript
Callbacks and promises
What you will learn
- What a callback is and why nesting callbacks becomes a problem
- What a promise is: pending, fulfilled and rejected
- Create promises and chain
then,catchandfinally - Run promises in parallel with
Promise.all,allSettled,raceandany - Convert callback APIs to promises and avoid common bugs
In simple words
Some things take time: loading data from a server, reading a file, waiting for a timer. JavaScript does not stop and wait; it asks for the thing and says "call me back when you have it". A promise is a receipt for a result that will arrive later: it is either still waiting, completed with a value, or failed with an error. You attach what to do next to the receipt.
Words to know
- Callback: a function passed to another function to be called when something finishes.
- Promise: an object representing the eventual result of an asynchronous operation.
- Fulfilled and rejected: a promise that succeeded with a value, and one that failed with an error.
- Chaining: linking asynchronous steps with
.thenone after another.
Callbacks
setTimeout(() => console.log("one second later"), 1000);
button.addEventListener("click", (event) => console.log("clicked"));
import { readFile } from "node:fs";
readFile("orders.json", "utf8", (error, text) => { // Node.js style: error first
if (error) return console.error(error);
console.log(JSON.parse(text));
});
Callbacks work, but when steps depend on each other they nest deeper and deeper, the "callback hell" or pyramid of doom, and error handling gets repeated at every level:
getUser(id, (err, user) => {
if (err) return handle(err);
getOrders(user.id, (err, orders) => {
if (err) return handle(err);
getPayment(orders[0].id, (err, payment) => {
if (err) return handle(err);
show(payment);
});
});
});
Promises (ES2015) flatten this.
Promises
A promise is in one of three states:
- pending: the work is not finished yet;
- fulfilled: it finished with a value;
- rejected: it failed with a reason (usually an
Error).
Once fulfilled or rejected, it is settled and never changes. Create one with the constructor, giving it an executor with resolve and reject:
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function parseJson(text) {
return new Promise((resolve, reject) => {
try { resolve(JSON.parse(text)); }
catch (error) { reject(error); }
});
}
Promise.resolve(42); // an already fulfilled promise
Promise.reject(new Error("failed")); // an already rejected promise
const { promise, resolve, reject } = Promise.withResolvers(); // ES2024: expose resolve and reject
Most of the time you do not create promises: APIs such as fetch return them.
then, catch and finally
fetch("/api/orders")
.then((response) => response.json()) // runs when fulfilled; returns a value or a promise
.then((orders) => orders.filter((o) => o.status === "paid"))
.then((paid) => console.log(paid.length))
.catch((error) => console.error("failed:", error)) // runs if ANY step above rejected
.finally(() => console.log("done")); // runs either way (good for hiding a spinner)
How chaining works:
.then(onFulfilled, onRejected)returns a new promise.- If the handler returns a value, the next promise fulfils with it; if it returns another promise, the chain waits for it; if it throws, the next promise rejects.
.catch(fn)is.then(undefined, fn); an error skips down the chain to the nextcatch.- After a
catchthat returns a value, the chain recovers and continues fulfilled. - Handlers always run asynchronously as microtasks (the event loop lesson).
Flat chains replace the pyramid:
getUser(id)
.then((user) => getOrders(user.id))
.then((orders) => getPayment(orders[0].id))
.then(show)
.catch(handle);
Return the promise inside a then, or the chain will not wait for it. A very common bug:
.then((user) => { getOrders(user.id); }) // forgot `return`: the next step runs immediately with undefined
.then((user) => getOrders(user.id)) // correct: returns the promise
Running promises together
When tasks do not depend on each other, start them together instead of one after another (waiting for each in turn doubles the time):
const [user, orders, offers] = await Promise.all([
fetch("/api/user").then(r => r.json()),
fetch("/api/orders").then(r => r.json()),
fetch("/api/offers").then(r => r.json()),
]);
| Combinator | Fulfils when | Rejects when | Use for |
|---|---|---|---|
Promise.all([...]) |
all fulfil (array of results, in order) | any rejects (fails fast) | needing every result |
Promise.allSettled([...]) |
all settle (array of {status, value|reason}) |
never | best-effort: show what worked |
Promise.race([...]) |
the first settles | the first rejects if it settles first | timeouts |
Promise.any([...]) |
the first fulfils | all reject (AggregateError) |
the fastest successful source |
const results = await Promise.allSettled([loadProfile(), loadRecommendations()]);
for (const r of results) {
if (r.status === "fulfilled") render(r.value);
else console.warn("a widget failed:", r.reason); // one failure does not break the page
}
const withTimeout = (promise, ms) =>
Promise.race([promise, new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), ms))]);
Note: Promise.all does not cancel the other promises when one rejects; they keep running. To cancel network requests, use an AbortController (the fetch lesson).
Converting callbacks to promises
const readFileAsync = (path) =>
new Promise((resolve, reject) => {
readFile(path, "utf8", (error, text) => (error ? reject(error) : resolve(text)));
});
// Node.js already offers promise versions:
import { readFile } from "node:fs/promises";
import { promisify } from "node:util";
const sleep = promisify(setTimeout);
Browser and Node.js APIs increasingly return promises natively (fetch, fs/promises, crypto.subtle, navigator.clipboard).
Unhandled rejections
A rejected promise with no handler raises an unhandled rejection: in browsers it logs Uncaught (in promise); in Node.js (since version 15) it crashes the process by default. Always handle errors: end chains with .catch, or use try/catch with await (next lesson). Do not fire promises and forget them without a catch. Listen for the last resort: window.addEventListener("unhandledrejection", ...) and process.on("unhandledRejection", ...) for logging, not for normal handling.
Common pitfalls
- Forgetting to
returna promise in.then. - Nesting
.theninside.theninstead of chaining flat. - Forgetting
.catch, losing errors. - Running independent tasks sequentially instead of with
Promise.all. new Promisewrapped around something that already returns a promise (the "explicit construction anti-pattern").- Throwing inside a callback of an old-style API where the promise cannot see it.
- Expecting
forEachwithasynccallbacks to wait:array.forEach(async x => ...)does not wait for them; usefor...ofwithawait, orPromise.all(array.map(async ...)).
Try it yourself
- Write
wait(ms)and use it to log "A", wait one second, log "B", wait again, log "C" with a promise chain. - Chain three functions that each return a promise and put one
.catchat the end; make the middle one fail and observe the skip. - Use
Promise.allfor threefetchcalls and measure the time compared with doing them one by one. - Use
Promise.allSettledso that one failing request does not hide the others. - Write
withTimeout(promise, ms)usingPromise.race.
Check yourself
What are the three states of a promise?
Pending, fulfilled (with a value) and rejected (with a reason); fulfilled and rejected are together called settled.
What does .then return?
A new promise that is fulfilled with the handler's return value (or the result of a returned promise) and rejected if the handler throws.
What is the difference between Promise.all and Promise.allSettled?
Promise.all rejects as soon as one promise rejects; Promise.allSettled always waits for all of them and reports each outcome.
What happens to an error thrown in a then handler?
The promise returned by that then rejects, and the error propagates down the chain to the next catch.
Interview questions
What is callback hell and how do promises help?
Deeply nested callbacks for sequential async steps, with repeated error handling. Promises allow flat chaining with then and a single catch, and async/await makes it read like synchronous code.
Explain Promise.all, Promise.race, Promise.allSettled and Promise.any.
all waits for all to fulfil and fails fast on the first rejection; race settles with the first settled promise; allSettled waits for all and reports each result; any fulfils with the first fulfilled promise and rejects only if all reject.
How do you run async operations sequentially versus in parallel?
Sequentially by chaining then or using await in order in a loop; in parallel by starting them together and combining them with Promise.all.
Summary
- Callbacks handle completion later but nest badly; promises represent a future value and chain flatly.
- A promise is pending, fulfilled or rejected;
then,catchandfinallyreturn new promises; always return fromthen. - Use
Promise.allfor parallel work,allSettledfor best effort,racefor timeouts,anyfor the first success. - Never leave rejections unhandled.
Going deeper
- MDN: Using promises: the guide with chaining and error handling.
- MDN: Promise reference: methods and combinators.
- MDN: Asynchronous JavaScript: a learning path from callbacks to async/await.
- ECMAScript specification: Promise objects: the formal behaviour.
See how much of this you can explain
A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.