Skip to content
jshacks.dev
Async

Callbacks and Callback Hell

Learn how JavaScript callbacks work, why nested callbacks turn into callback hell, and four ways to flatten them with named functions, promises and async await.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, TypeScript and npm logos.

A callback is the simplest idea in asynchronous JavaScript, a function you hand to someone else to call later. The trouble comes when step two needs the result of step one and step three needs step two, because each step goes inside the previous callback and the code drifts right across the screen. That shape has a name, callback hell, and it is a real maintenance problem and not only an aesthetic one: error handling gets duplicated, variables leak between levels and a single missed return runs a callback twice. This post covers what callbacks are on Node.js 24, shows the pyramid failing, then flattens it four ways: named functions, a small control-flow helper, promises and async/await. It closes with the callback bugs that survive refactoring.

What a callback is

A callback is any function passed as an argument to be invoked later. It is not special syntax. Array methods use them synchronously, and timers and I/O use them asynchronously.

JavaScript
const numbers = [1, 2, 3];

numbers.forEach((n) => console.log("sync callback", n));

setTimeout(() => console.log("async callback"), 0);

console.log("end of script");
Text
sync callback 1
sync callback 2
sync callback 3
end of script
async callback

The array callbacks run before forEach returns. The timer callback runs after the whole script. Both are callbacks, and the only difference is when they are called. Asynchronous callbacks are the ones that lead to trouble, because the code that follows them does not wait.

The pyramid

Suppose you must read a config file, use it to find a user file, read the user and then write a report. Each step is asynchronous and each depends on the last.

JavaScript
import { readFile, writeFile } from "node:fs";

readFile("config.json", "utf8", (err, configText) => {
  if (err) {
    console.log("config failed:", err.code);
    return;
  }
  const config = JSON.parse(configText);

  readFile(config.userFile, "utf8", (err2, userText) => {
    if (err2) {
      console.log("user failed:", err2.code);
      return;
    }
    const user = JSON.parse(userText);

    writeFile("report.txt", `report for ${user.name}`, (err3) => {
      if (err3) {
        console.log("write failed:", err3.code);
        return;
      }
      console.log("report written");
    });
  });
});

With config.json containing {"userFile": "user.json"} and user.json containing {"name": "Ada"}, the output is:

Text
report written

Three steps already need three levels of indentation and three separate error checks, each with its own variable name (err, err2, err3) because the inner scope can see the outer one. Add a fourth step and the problems compound. The success path is buried in the deepest level, the error handling is repeated, and moving one step means rewriting the nesting. Also notice a hidden failure: JSON.parse can throw, and inside a callback there is no surrounding try/catch that would see it, so a malformed file crashes the process instead of reaching the error branch.

Fix 1: name the functions and flatten

The cheapest fix needs no library. Give each step a name, define them at the same level and let each call the next.

JavaScript
import { readFile, writeFile } from "node:fs";

function fail(label, err) {
  console.log(`${label} failed:`, err.code);
}

function readConfig() {
  readFile("config.json", "utf8", (err, text) => {
    if (err) return fail("config", err);
    readUser(JSON.parse(text));
  });
}

function readUser(config) {
  readFile(config.userFile, "utf8", (err, text) => {
    if (err) return fail("user", err);
    writeReport(JSON.parse(text));
  });
}

function writeReport(user) {
  writeFile("report.txt", `report for ${user.name}`, (err) => {
    if (err) return fail("write", err);
    console.log("report written");
  });
}

readConfig();
Text
report written

The nesting is gone and each function does one thing. The cost is that the order of the steps is no longer visible in one place; you follow the calls from readConfig down. This is a real improvement for two or three steps and weaker beyond that.

Fix 2: a control-flow helper

Before promises, libraries such as async offered waterfall and parallel. A minimal version shows the idea of passing results from one step to the next.

JavaScript
function waterfall(steps, done) {
  let index = 0;

  function next(err, ...results) {
    if (err || index === steps.length) return done(err, ...results);
    const step = steps[index++];
    step(...results, next);
  }

  next(null);
}

waterfall(
  [
    (cb) => setTimeout(() => cb(null, 2), 5),
    (n, cb) => setTimeout(() => cb(null, n * 10), 5),
    (n, cb) => setTimeout(() => cb(null, n + 1), 5),
  ],
  (err, result) => console.log(err, result),
);
Text
null 21

Each step receives the previous result and a next function. An error short-circuits to done. It is flat, but it has its own convention to learn, and it is exactly what promises later standardized.

Fix 3: promises

Wrap a callback API once, and every step becomes a chain.

JavaScript
import { promisify } from "node:util";
import { readFile, writeFile } from "node:fs";

const read = promisify(readFile);
const write = promisify(writeFile);

read("config.json", "utf8")
  .then((text) => read(JSON.parse(text).userFile, "utf8"))
  .then((text) => write("report.txt", `report for ${JSON.parse(text).name}`))
  .then(() => console.log("report written"))
  .catch((err) => console.log("failed:", err.code));
Text
report written

One catch covers every step, and a thrown error inside a then, including the one from JSON.parse, lands in it too. That fixes the two worst problems of the pyramid at once.

Fix 4: async and await

The same code reads as straight-line steps.

JavaScript
import { readFile, writeFile } from "node:fs/promises";

async function buildReport() {
  const config = JSON.parse(await readFile("config.json", "utf8"));
  const user = JSON.parse(await readFile(config.userFile, "utf8"));
  await writeFile("report.txt", `report for ${user.name}`);
  console.log("report written");
}

try {
  await buildReport();
} catch (err) {
  console.log("failed:", err.code);
}
Text
report written

This is where most code should end up. The steps appear in the order they happen, variables from earlier steps are in scope without nesting, and try/catch handles every failure. A missing file would print failed: ENOENT.

Bugs that survive the refactor

Calling a callback twice. A missing return after an error branch runs the success path as well.

JavaScript
function load(done) {
  setTimeout(() => {
    const err = new Error("boom");
    if (err) done(err);
    done(null, "data"); // missing return, runs anyway
  }, 5);
}

load((err, data) => console.log(err ? "error" : "ok", data));
Text
error undefined
ok data

The callback ran twice, once for each branch. Always return done(err).

Mixing sync and async. A function that calls its callback immediately in one case and later in another is unpredictable, because the code after the call runs in different orders. Always be one or the other. Node.js calls this "releasing Zalgo" in its own guidance, and the fix is queueMicrotask or process.nextTick to defer the synchronous case.

Losing errors in a callback that throws. A throw inside an asynchronous callback is not caught by a try/catch around the call that scheduled it.

JavaScript
try {
  setTimeout(() => {
    throw new Error("late failure");
  }, 0);
} catch {
  console.log("never reached");
}
Text
Uncaught Error: late failure

In a Node.js script this prints the error with a stack trace and exits with a non-zero code. The try block finished long before the timer fired.

When callbacks are still right

Event listeners fire many times and do not map onto a promise that settles once, so element.addEventListener("click", handler) and emitter.on("data", handler) stay callbacks. Array methods, sort comparators and replace with a function are all callbacks too, and they are fine because they run synchronously. The advice is not to avoid callbacks. It is to avoid chaining dependent asynchronous steps through them.

A practical rule for new code

If you are writing new code today, you will rarely need to design a callback API. The platform has moved on, and the promise forms of the file, timer, DNS and stream helpers are already in the standard library. That changes the question from "how do I avoid callback hell" to "how do I cope with the callback code that is already there".

The answer is to convert at the edges. Wrap the old function once, in one place, with promisify or a small new Promise, and let the rest of the program use the promise version. The old callback code keeps working, and nobody downstream has to think about nesting. When you meet a function that takes both a callback and returns a promise depending on arguments, treat it with suspicion and read its documentation, since the two modes often differ in how they report errors. And when you review a pull request that adds a fourth level of nesting, ask for named functions or await before anything else, because the review comments that come after that point are almost always about the nesting.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.