Node.js Callbacks Explained: Error-First Pattern, Callback Hell and Promises
A callback in Node.js is a function you pass to another function so it can call you back later, usually when some I/O is done: a file was read, a query finished, a timer fired. Node’s core APIs use the error-first convention: the callback’s first argument is an error (or null if things worked), and the result comes after it.
Callbacks are older than promises in Node, but they’re still everywhere: event handlers, Array.prototype.forEach, and the classic fs API. The examples below were run on Node 22, and the output is from those runs.
Sync and async callbacks
Not every callback is asynchronous. forEach calls yours immediately, once per element, before it returns. setTimeout calls yours later, after the current code has finished:
[3, 1, 2].forEach((n) => console.log('sync callback', n));
console.log('before setTimeout');
setTimeout(() => console.log('async callback runs'), 0);
console.log('after setTimeout');
sync callback 3
sync callback 1
sync callback 2
before setTimeout
after setTimeout
async callback runs
Even with a 0 ms delay, the timer callback waits until the running code is done. That’s the event loop at work: Node starts an operation, keeps running your code, and calls the callback when the result is ready. This is why Node can serve many requests on one thread, and why you can’t return a result out of an async callback. The value doesn’t exist yet when the outer function returns.
The error-first pattern
Here’s a function written the Node way. It takes a callback last and calls it with (err) on failure or (null, result) on success:
function getUser(id, callback) {
setTimeout(() => {
if (id !== 1) {
callback(new Error(`user ${id} not found`));
return;
}
callback(null, { id, name: 'Rez' });
}, 10);
}
getUser(1, (err, user) => {
if (err) {
console.error('Error:', err.message);
return;
}
console.log('User:', user.name);
});
getUser(1, ...) prints User: Rez, and getUser(2, ...) prints Error: user 2 not found. Two habits keep this pattern safe. Always check err first and return after handling it, or the success code runs with user undefined. And call the callback exactly once. Calling it twice, or never, is the most common callback bug, and the return after callback(new Error(...)) above is there to prevent it.
Node’s own APIs follow the same shape. Reading a file that doesn’t exist with fs.readFile gives an error whose code is ENOENT, so you can check err.code to tell “missing” apart from other failures. There’s more on that in working with files in Node.js.
try/catch around an async call does not catch errors that happen inside its callback, because by the time the callback runs, the try block has already finished. That’s another reason the error travels as an argument.
Callback hell and how to flatten it
When each step needs the previous result, callbacks nest:
getUser(1, (err, user) => {
if (err) return done(err);
getOrders(user.id, (err, orders) => {
if (err) return done(err);
getInvoice(orders[0].id, (err, invoice) => {
if (err) return done(err);
done(null, invoice);
});
});
});
Every level repeats the error check, and the code drifts right. The old fix is to give each step a name and keep nesting to one level. The modern fix is to stop writing callbacks for this and use promises.
From callbacks to promises and async/await
util.promisify wraps any error-first function and returns a version that gives back a promise:
const util = require('node:util');
const getUserAsync = util.promisify(getUser);
async function main() {
const user = await getUserAsync(1);
console.log('Promisified:', user.name);
try {
await getUserAsync(5);
} catch (err) {
console.log('Caught:', err.message);
}
}
Promisified: Rez
Caught: user 5 not found
The callback’s err turns into a rejected promise, so plain try/catch works again. The nested example above becomes three lines of await, one after another.
Most core modules already ship promise versions, so you rarely need promisify for them: require('node:fs/promises'), require('node:timers/promises') and require('node:dns/promises'). For new code I use async/await by default and keep callbacks for events, like server.on('request', ...) in a simple Node.js web server, where a function really is called many times.
Go solves the same problem without callbacks: you write blocking code and run it in a goroutine, which is cheap enough to start one per request. Goroutines vs threads explains why that works, and reading and writing JSON in Node.js shows the async file API in a real task.
