What is Callback Hell?

Callback hell is deeply nested asynchronous callbacks, where each step is written inside the previous step's callback, producing code that drifts right ("the pyramid of doom") and becomes hard to read, debug and handle errors in.

Why it happens

With callback-based APIs, the only way to run step B after step A is to put B inside A's callback. Several dependent steps (load user, then orders, then details, then save) nest several levels deep.

Problems beyond indentation

  • Error handling repeats at every level (if (err) return handle(err)), and one missed check silently swallows failures.
  • try/catch does not work across async boundaries.
  • Hard to run things in parallel or add timeouts and retries.
  • Inversion of control: you trust each API to call your callback exactly once.

Fixes, in historical order

  1. Named functions instead of anonymous inline callbacks (flattens the code, does not fix error handling).
  2. Promises: chain with .then and handle errors once with .catch.
  3. async/await: write the steps top to bottom with one try/catch.

Converting old APIs

Wrap callback APIs with new Promise(...) or Node's util.promisify. Most modern APIs (fetch, Node's fs/promises) already return promises.

Code example

js
1// Simulated callback-based API (error-first)
2const db = {
3 getUser: (id, cb) => setTimeout(() => cb(null, { id, name: "Ada" }), 5),
4 getOrders: (user, cb) => setTimeout(() => cb(null, [{ id: 7, total: 40 }]), 5),
5 getDetails: (order, cb) => setTimeout(() => (order.id === 7 ? cb(null, { ...order, items: 3 }) : cb(new Error("missing"))), 5),
6};
7
8// Callback hell: nesting + repeated error handling
9db.getUser(1, (err, user) => {
10 if (err) return console.log(err);
11 db.getOrders(user, (err, orders) => {
12 if (err) return console.log(err);
13 db.getDetails(orders[0], (err, details) => {
14 if (err) return console.log(err);
15 console.log("callbacks:", user.name, details.items, "items");
16 });
17 });
18});
19
20// Fix: promisify once, then write flat async code with one error handler
21const promisify = (fn) => (...args) => new Promise((resolve, reject) => fn(...args, (err, data) => (err ? reject(err) : resolve(data))));
22const getUser = promisify(db.getUser);
23const getOrders = promisify(db.getOrders);
24const getDetails = promisify(db.getDetails);
25
26try {
27 const user = await getUser(1);
28 const [firstOrder] = await getOrders(user);
29 const details = await getDetails(firstOrder);
30 console.log("async/await:", user.name, details.items, "items");
31} catch (err) {
32 console.log("one place to handle every error:", err.message);
33}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app