Asynchronous JavaScript
Node.js Callbacks and Callback Hell
A callback is a function passed to an asynchronous operation and invoked when it finishes. Node’s convention is error-first: the callback receives an error as its first argument and the result as the second.
What is Callbacks and Callback Hell in Node.js?
A callback is a function passed to an asynchronous operation and invoked when it finishes. Node’s convention is error-first: the callback receives an error as its first argument and the result as the second.
Callbacks and Callback Hell example
fs.readFile('a.json', 'utf8', (err, a) => {
if (err) return console.error(err);
fs.readFile('b.json', 'utf8', (err, b) => {
if (err) return console.error(err);
fs.writeFile('c.json', a + b, err => {
if (err) return console.error(err);
console.log('done'); // three levels deep already
});
});
});The same logic with async/await
try {
const [a, b] = await Promise.all([
readFile('a.json', 'utf8'),
readFile('b.json', 'utf8'),
]);
await writeFile('c.json', a + b);
console.log('done');
} catch (err) {
console.error(err);
}Flat, readable, one error handler — and the two reads now run concurrently instead of one after the other.
Key points to remember
- Always check the error argument first and return early.
- util.promisify converts a callback API into a promise-based one.
- try/catch cannot catch an error passed to a callback.
Common mistakes with Callbacks and Callback Hell
- Forgetting return after handling an error, so the success path runs too.
- Wrapping callback code in try/catch and believing it is handled.
Node.js Callbacks and Callback Hell— Interview Questions & FAQs
What is callback hell?+
Deeply nested callbacks that make code drift rightwards and duplicate error handling at every level. Promises and async/await flatten it into sequential-looking code with one catch.
