A callback is a function passed to another function, to be called when work is finished.
Error-first callbacks
Node's classic APIs call your function with the error first: (err, result) => {}. Always check err before using result.
Callback hell
When each step depends on the previous one, callbacks nest deeper and deeper (the "pyramid of doom"). The code becomes hard to read and error handling repeats everywhere.
The solution: Promises
- Most Node APIs have a promise version (
node:fs/promises) util.promisify(fn)converts an error-first callback function into one that returns a promise- Then use async/await (next lesson)
You will still see callbacks in event listeners (server.on('request', cb)), array methods (map, filter) and older libraries.
Example
import fs from 'node:fs';
import { promisify } from 'node:util';
// ❌ Callback style: nested and repetitive
fs.readFile('a.txt', 'utf8', (err, a) => {
if (err) return console.error(err.message);
fs.readFile('b.txt', 'utf8', (err, b) => {
if (err) return console.error(err.message);
fs.writeFile('ab.txt', a + b, (err) => {
if (err) return console.error(err.message);
console.log('Merged (callbacks)');
});
});
});
// ✅ Same task with promisify + async/await
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
try {
const a = await readFile('a.txt', 'utf8');
const b = await readFile('b.txt', 'utf8');
await writeFile('ab.txt', a + b);
console.log('Merged (async/await)');
} catch (err) {
console.error(err.message);
}
Both versions merge a.txt and b.txt into ab.txt. The async/await version is flat and has one place for error handling.