Lesson 7 of 12 · 9 min · Asynchronous JavaScript

Callbacks and promises

Covers: JavaScript (ECMAScript 2025) in current browsers and Node.js 22 or newer. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

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, catch and finally
  • Run promises in parallel with Promise.all, allSettled, race and any
  • 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 .then one 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 next catch.
  • After a catch that 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 return a promise in .then.
  • Nesting .then inside .then instead of chaining flat.
  • Forgetting .catch, losing errors.
  • Running independent tasks sequentially instead of with Promise.all.
  • new Promise wrapped 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 forEach with async callbacks to wait: array.forEach(async x => ...) does not wait for them; use for...of with await, or Promise.all(array.map(async ...)).

Try it yourself

  1. Write wait(ms) and use it to log "A", wait one second, log "B", wait again, log "C" with a promise chain.
  2. Chain three functions that each return a promise and put one .catch at the end; make the middle one fail and observe the skip.
  3. Use Promise.all for three fetch calls and measure the time compared with doing them one by one.
  4. Use Promise.allSettled so that one failing request does not hide the others.
  5. Write withTimeout(promise, ms) using Promise.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, catch and finally return new promises; always return from then.
  • Use Promise.all for parallel work, allSettled for best effort, race for timeouts, any for the first success.
  • Never leave rejections unhandled.

Going deeper

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.