Sub topic 10
Callback Hell and How to Flatten It
This chapter assumes you already know the Node.js error-first callback convention, fs.readFile, and how closures capture variables. It shows why nested callbacks become hard to read and how to restructure them with plain functions, before Promises enter the picture.
What Callback Hell Looks Like
When one asynchronous step depends on the result of another, the natural move is to start the next step inside the previous callback. Do that three or four times and the code drifts to the right. People call this shape "callback hell" or the "pyramid of doom."
The script below reads a config file. It then reads the input file named in that config and writes an uppercased copy to the output path.
const fs = require('node:fs');
fs.readFile('config.json', 'utf8', (err, text) => {
if (err) {
console.error('Config read failed:', err.message);
return;
}
let config;
try {
config = JSON.parse(text);
} catch (parseErr) {
console.error('Bad JSON:', parseErr.message);
return;
}
fs.readFile(config.input, 'utf8', (err, data) => {
if (err) {
console.error('Input read failed:', err.message);
return;
}
fs.writeFile(config.output, data.toUpperCase(), (err) => {
if (err) {
console.error('Write failed:', err.message);
return;
}
console.log('Done');
});
});
});To try it, create config.json containing {"input": "in.txt", "output": "out.txt"} and an in.txt file with any text.
Why the Nesting Hurts
The trouble goes beyond the indentation:
- Repeated error handling. Every level needs its own
if (err)block. If you forget one, the error disappears without a trace. - Shadowed names. Each level declares its own
err, which hides the outer one. A typo can quietly make you check the wrong variable. - Hard to reuse or test. The step that writes the file only exists inside an anonymous function, so you can't call it by itself.
- Hidden control flow. You have to read the whole pyramid to see what runs in what order.
Flattening with Named Functions
You fix this by giving each step a name, defining it at the top level, and passing results forward. Each function does one job and ends by calling the next step or a shared error handler.
const fs = require('node:fs');
function handleError(stage, err) {
console.error(`${stage} failed:`, err.message);
}
function loadConfig(path) {
fs.readFile(path, 'utf8', (err, text) => {
if (err) return handleError('Config read', err);
let config;
try {
config = JSON.parse(text);
} catch (parseErr) {
return handleError('Config parse', parseErr);
}
readInput(config);
});
}
function readInput(config) {
fs.readFile(config.input, 'utf8', (err, data) => {
if (err) return handleError('Input read', err);
writeOutput(config, data);
});
}
function writeOutput(config, data) {
fs.writeFile(config.output, data.toUpperCase(), (err) => {
if (err) return handleError('Write', err);
console.log('Done');
});
}
loadConfig('config.json');The behavior matches the nested version. The nesting depth is now at most two levels, and each step can be read on its own.
Techniques That Help
| Technique | What it does |
|---|---|
| Named functions | Removes anonymous nesting and gives each step a clear purpose |
| Early return (`if (err) return ...`) | Handles the error and stops, so the success path stays unindented |
| Shared error handler | Puts the error logging or reporting in one place |
| Pass data explicitly | Sends `config` and `data` as arguments instead of relying on outer closures |
| Small modules | Moves related steps into their own file once a workflow grows |
What Flattening Does Not Solve
Named functions make the code easier to read, but some problems remain. Running steps in parallel and waiting for all of them still needs a manual counter. Each function also hard-codes which step comes next, so the order is spread across the file. And try/catch placed around loadConfig(...) will not catch errors thrown later inside callbacks, because those callbacks run on a later turn of the event loop. These limits are why Promises and async/await exist. A later chapter covers converting callback code to Promises.
Exercise
In the flattened version, readInput calls writeOutput(config, data) directly. Suppose you want to reuse readInput in another script that should log the file length instead of writing a file. How would you change readInput so that the next step is not hard-coded?
Show answer
Give readInput a callback parameter and call that instead of writeOutput: function readInput(config, next) { fs.readFile(config.input, 'utf8', (err, data) => { if (err) return handleError('Input read', err); next(config, data); }); }. Then loadConfig calls readInput(config, writeOutput), and the other script calls readInput(config, (cfg, data) => console.log(data.length)).
Exercise
A developer writes try { loadConfig('missing.json'); } catch (e) { console.log('caught'); }. The file does not exist. Is "caught" printed? Why or why not?
Show answer
No. fs.readFile starts the read and returns right away, so the try block finishes without an error. The failure arrives later as the err argument of the callback, which calls handleError. No exception ever passes through the try/catch.