Sub topic 10
Callback Hell and How to Flatten It
This chapter assumes you can write error-first callbacks in Node.js. It also assumes you know how closures capture variables and why asynchronous callbacks run later, from the event loop. All examples run in Node.js 18 or later. Save each one as a .js file and run it with node.
Callbacks are easy to reason about one at a time. Trouble starts when one asynchronous step needs the result of another, which needs the result of another. Each dependent step goes inside the previous step's callback, and the code drifts to the right. This shape is called "callback hell" or the "pyramid of doom." This chapter shows why the shape causes real bugs, not only ugly code. It then shows how to flatten it with named functions, a uniform step signature, and two small control-flow helpers.
What Callback Hell Looks Like
Here is a realistic task. Read a JSON config file, read the input file it names, uppercase the text, write the result to the output file it names, then report the output's size. Every step depends on the one before it.
const fs = require('node:fs');
// Setup so the example runs as shown
fs.writeFileSync('config.json', JSON.stringify({ input: 'input.txt', output: 'output.txt' }));
fs.writeFileSync('input.txt', 'hello callbacks');
fs.readFile('config.json', 'utf8', (err, configText) => {
if (err) {
console.error('Config read failed:', err.message);
} else {
let config;
try {
config = JSON.parse(configText);
} catch (parseErr) {
console.error('Config parse failed:', parseErr.message);
return;
}
fs.readFile(config.input, 'utf8', (err, inputText) => {
if (err) {
console.error('Input read failed:', err.message);
} else {
const result = inputText.toUpperCase();
fs.writeFile(config.output, result, (err) => {
if (err) {
console.error('Write failed:', err.message);
} else {
fs.stat(config.output, (err, stats) => {
if (err) {
console.error('Stat failed:', err.message);
} else {
console.log('Wrote', stats.size, 'bytes');
}
});
}
});
}
});
}
});It works and prints Wrote 15 bytes. It is also hard to maintain.
Why Nesting Causes Bugs
The indentation is a symptom. The underlying problems are these:
- Shadowed names. Every level declares its own
err. If you delete one parameter by mistake, the inner code silently reads the outererr, which isnull, and continues as if nothing failed. - Duplicated error handling. There are five error branches, and each one handles the failure in its own way. Changing the error policy, for example to log and exit with a non-zero code, means editing all five.
- No reuse or testing. "Load and parse the config" is a useful operation. Because it is buried in an anonymous function, you cannot call it from elsewhere or test it on its own.
- Implicit shared state. Inner callbacks reach
configthrough closures. Moving a step to another place breaks it, because the variables it depends on are no longer in scope. - No single completion point. No caller can find out when the whole job finishes or whether it failed. The outcome is scattered across several leaves of the tree.
Technique 1: Early Returns
The first fix is local. Use if (err) return ... instead of if/else. When the error branch exits the function, the success path does not need an else, so each level loses one indent.
fs.readFile(config.input, 'utf8', (err, inputText) => {
if (err) return console.error('Input read failed:', err.message);
const result = inputText.toUpperCase();
// continue at the same indentation
});The return matters even when you call a callback rather than log. Without it, the code calls the callback for the error and then keeps going, usually to a second call with undefined data. Calling a callback twice is one of the most common callback bugs. The return is what prevents it.
Technique 2: Name Each Step and Give It One Signature
The main fix is to lift each anonymous function to the top level and give it a name. Then give every step the same shape, step(input, done). Each step does one asynchronous thing and reports through done(err, output). It never decides what happens next.
const fs = require('node:fs');
function loadConfig(path, done) {
fs.readFile(path, 'utf8', (err, text) => {
if (err) return done(err);
let config;
try {
config = JSON.parse(text);
} catch (parseErr) {
return done(parseErr);
}
done(null, config);
});
}
function transformInput(config, done) {
fs.readFile(config.input, 'utf8', (err, text) => {
if (err) return done(err);
done(null, { config, result: text.toUpperCase() });
});
}
function writeOutput({ config, result }, done) {
fs.writeFile(config.output, result, (err) => {
if (err) return done(err);
done(null, config.output);
});
}
function measureFile(path, done) {
fs.stat(path, (err, stats) => {
if (err) return done(err);
done(null, stats.size);
});
}
module.exports = { loadConfig, transformInput, writeOutput, measureFile };Save this as steps.js. Each function is now short, testable, and reusable. Each step passes its data forward explicitly. transformInput returns { config, result } because the next step needs both values. That replaces the hidden closure dependencies of the pyramid.
Named steps alone do not flatten the call site. Chaining them by hand still nests four levels, though each level is now a single line. To remove the nesting completely, let a helper do the chaining.
Technique 3: A Sequencing Helper
Because every step has the same signature, a small function can run them in order. It passes each output to the next step and stops at the first error.
function series(steps, initial, done) {
let index = 0;
function next(err, value) {
if (err) return done(err);
if (index === steps.length) return done(null, value);
const step = steps[index];
index += 1;
step(value, next);
}
next(null, initial);
}
module.exports = { series };Save this as flow.js. The pipeline becomes a flat list:
const fs = require('node:fs');
const { loadConfig, transformInput, writeOutput, measureFile } = require('./steps');
const { series } = require('./flow');
fs.writeFileSync('config.json', JSON.stringify({ input: 'input.txt', output: 'output.txt' }));
fs.writeFileSync('input.txt', 'hello callbacks');
series([loadConfig, transformInput, writeOutput, measureFile], 'config.json', (err, size) => {
if (err) {
console.error('Pipeline failed:', err.message);
process.exitCode = 1;
return;
}
console.log('Wrote', size, 'bytes');
});Error handling now lives in one place, the final callback. Every step reports errors the same way, and series sends them to that one exit. You can add, remove, or reorder a step by editing one line in the array.
series has two edge cases worth knowing:
- A synchronous throw escapes. If a step throws before it schedules any asynchronous work, the exception propagates out of
series. Steps should report failures throughdone, not by throwing. - Stack depth. If a step calls
donesynchronously, for example on a cache hit,nextruns inside the previous call and the stack grows. That is harmless for a few steps. With thousands of synchronous steps it can overflow. The next chapter shows how to keep callbacks consistently asynchronous, which also avoids this.
Technique 4: Running Independent Steps in Parallel
Nesting also hides a performance bug. Developers often nest operations that do not depend on each other, so they run one after another for no reason. Independent work can start at once. The difficulty is knowing when all of it has finished, and making sure the final callback runs exactly once.
function parallel(tasks, done) {
const results = new Array(tasks.length);
let pending = tasks.length;
let finished = false;
if (pending === 0) {
queueMicrotask(() => done(null, results));
return;
}
tasks.forEach((task, i) => {
task((err, value) => {
if (finished) return;
if (err) {
finished = true;
return done(err);
}
results[i] = value;
pending -= 1;
if (pending === 0) {
finished = true;
done(null, results);
}
});
});
}
module.exports = { parallel };Save this as parallel.js. Here it measures three files at the same time:
const fs = require('node:fs');
const { measureFile } = require('./steps');
const { parallel } = require('./parallel');
fs.writeFileSync('a.txt', 'a');
fs.writeFileSync('b.txt', 'bb');
fs.writeFileSync('c.txt', 'ccc');
parallel(
['a.txt', 'b.txt', 'c.txt'].map((name) => (done) => measureFile(name, done)),
(err, sizes) => {
if (err) return console.error(err.message);
console.log(sizes); // [ 1, 2, 3 ]
}
);Each line of parallel handles a specific failure mode:
| Detail | Bug it prevents |
|---|---|
| `results[i] = value` instead of `push` | Results come back in completion order, which differs from input order |
| `pending` counter | Calling `done` before every task has finished |
| `finished` flag | Calling `done` again when a second task fails, or when the rest succeed after an earlier error |
| `queueMicrotask` for an empty list | Calling `done` synchronously in one case and asynchronously in all others |
On an error, parallel reports it immediately, but the other tasks keep running. Callbacks have no built-in cancellation. If the remaining work is expensive, you need your own abort mechanism, such as an AbortController passed to APIs that accept a signal.
Choosing a Technique
| Technique | What it fixes | When to use it |
|---|---|---|
| Early return | One indent per level, accidental double calls | Always |
| Named steps with `(input, done)` | Reuse, testing, hidden closure state | Any chain longer than two steps |
| `series` helper | Remaining nesting, scattered error handling | Dependent steps that run in order |
| `parallel` helper | Needless serial waits, counting completions | Independent steps |
| Promises and async/await | All of the above, with language support | New code, covered in the final chapter |
These helpers are simplified versions of the async npm library, which was the standard tool before Promises became common. The same ideas appear in Promise code. series corresponds to a chain of await statements, and parallel corresponds to Promise.all. If you understand the helpers, you understand what those built-ins do for you.
Exercise
This function sometimes calls its callback twice. Explain when, and fix it. function readJson(path, callback) { fs.readFile(path, 'utf8', (err, text) => { if (err) callback(err); try { callback(null, JSON.parse(text)); } catch (e) { callback(e); } }); }
Show answer
It has two bugs. First, after callback(err) there is no return, so execution continues. JSON.parse(undefined) throws, and the catch calls callback a second time. Second, callback(null, ...) is inside try, so if the caller's callback throws, the catch calls callback again with that error. Fix: write if (err) return callback(err);, then let data; try { data = JSON.parse(text); } catch (e) { return callback(e); }, then callback(null, data); outside the try block.
Exercise
Your teammate removes the finished flag from parallel because "the pending counter already handles completion." Two of three tasks fail. What happens?
Show answer
The first failure calls done(err). The second failure calls done(err) again, because nothing records that the job has already reported. Without the flag, a failure followed by the remaining tasks succeeding can also cause trouble: pending never reaches zero, because failed tasks do not decrement it, but repeated errors still reach done. The caller sees its final callback more than once, which can mean double responses, double logging, or crashes like "headers already sent" in an HTTP server.
Exercise
Add a step named backupOutput(path, done) that copies the output file to path + '.bak' using fs.copyFile, and insert it between writeOutput and measureFile so that the pipeline still reports the output's size.
Show answer
function backupOutput(path, done) { fs.copyFile(path, path + '.bak', (err) => { if (err) return done(err); done(null, path); }); } Then use series([loadConfig, transformInput, writeOutput, backupOutput, measureFile], 'config.json', finalCallback). The step passes path through unchanged, so measureFile still receives the output path.