Callbacks Explained: The Foundation of Async JavaScript
A callback is a function passed to another function to be called later. Learn how they work, callback hell, and how to avoid its pitfalls.
By Velloreth
What a callback is
A callback is a function passed as an argument to another function, to be called later. That is the whole definition.
function greet(name, callback) {
const message = `Hello, ${name}`;
callback(message);
}
greet('Ada', (msg) => console.log(msg));
greet receives a function and calls it. The function is the callback.
The reason this matters is that it lets you pass behaviour, not just data. greet decides when to call; the caller decides what to do.
Synchronous callbacks
Some callbacks run immediately, during the call.
[1, 2, 3].map((n) => n * 2);
[1, 2, 3].filter((n) => n > 1);
[1, 2, 3].sort((a, b) => a - b);
The function passed to map runs synchronously, once per element, before map returns. These are synchronous callbacks.
They are just a way of parameterising behaviour. There is nothing asynchronous about them.
Asynchronous callbacks
Other callbacks run later, after the current code finishes.
setTimeout(() => console.log('later'), 1000);
console.log('now');
// now
// later
The callback is registered, the timer starts, and execution continues. When the timer fires, the callback is queued and eventually runs.
This is the pattern that makes JavaScript concurrency possible on a single thread. The runtime handles the waiting; your callback handles the result.
Node’s error-first convention
Node standardised a callback signature: the first argument is an error, the second is the result.
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Failed to read:', err);
return;
}
console.log(data);
});
The convention has three parts:
- The error is the first argument, and it is
nullorundefinedon success. - The result is the second argument.
- The callback is called exactly once.
The if (err) return at the top is idiomatic. It handles the failure and exits early, so the success path is not nested inside an else.
This convention is why Node code is full of if (err) return lines. It makes failure explicit rather than thrown, which suits asynchronous code where a try/catch cannot span the async boundary.
Callback hell
The problem appears when operations depend on each other.
getUser(userId, (err, user) => {
if (err) return handle(err);
getPosts(user.id, (err, posts) => {
if (err) return handle(err);
getComments(posts[0].id, (err, comments) => {
if (err) return handle(err);
getAuthor(comments[0].authorId, (err, author) => {
if (err) return handle(err);
render(author, comments);
});
});
});
});
Four operations, four levels of nesting, four identical error checks. The code drifts rightward into a pyramid.
The problems are concrete:
- Error handling is repeated at every level, and easy to forget at one.
- Control flow is hard to follow — the sequence is expressed by nesting rather than by order.
- Refactoring is painful — extracting a step means threading callbacks through.
- Loops are awkward — running these in sequence or in parallel requires manual bookkeeping.
Escaping callback hell
Named functions
The simplest improvement is extracting callbacks into named functions, which flattens the nesting:
function handleUser(err, user) {
if (err) return handle(err);
getPosts(user.id, handlePosts);
}
function handlePosts(err, posts) {
if (err) return handle(err);
getComments(posts[0].id, handleComments);
}
function handleComments(err, comments) {
if (err) return handle(err);
render(comments);
}
getUser(userId, handleUser);
The nesting is gone, but the flow is now scattered across functions, which is its own readability cost.
Promises
Promises flatten the chain:
getUser(userId)
.then((user) => getPosts(user.id))
.then((posts) => getComments(posts[0].id))
.then((comments) => render(comments))
.catch(handle);
One error handler at the end covers every step. The sequence reads top to bottom.
async/await
async function load(userId) {
try {
const user = await getUser(userId);
const posts = await getPosts(user.id);
const comments = await getComments(posts[0].id);
render(comments);
} catch (error) {
handle(error);
}
}
This reads like synchronous code. It is the clearest of the three.
Promisifying a callback API
When you have a callback API and want to await it:
import { promisify } from 'node:util';
const readFile = promisify(fs.readFile);
const data = await readFile('data.txt', 'utf8');
Or manually:
function readFileAsync(path) {
return new Promise((resolve, reject) => {
fs.readFile(path, 'utf8', (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
}
Where callbacks are still the right tool
Promises did not replace callbacks everywhere. Some patterns are naturally callback-shaped.
Event listeners. An event may fire many times, which a promise cannot express:
button.addEventListener('click', handleClick);
Streams. Data arrives in chunks over time:
stream.on('data', (chunk) => process(chunk));
stream.on('end', () => finish());
stream.on('error', (err) => handle(err));
Middleware. Express handlers are callbacks:
app.get('/users', (req, res) => {
res.json(users);
});
Timers and intervals. setInterval fires repeatedly.
Node’s older APIs. Many still use error-first callbacks, though promise versions exist for most.
The pattern is: callbacks suit repeated or event-driven invocation, while promises suit single completion.
The pitfalls
Calling the callback more than once
function loadData(callback) {
cache.get('key', (err, cached) => {
if (cached) callback(null, cached); // first call
});
fetchFromNetwork((err, fresh) => {
callback(null, fresh); // second call — bug!
});
}
If both paths run, the callback fires twice. Code that assumes single invocation — like a promise wrapper — breaks subtly.
The fix is a guard:
function loadData(callback) {
let called = false;
const done = (...args) => {
if (called) return;
called = true;
callback(...args);
};
// use done everywhere instead of callback
}
Forgetting to return after an error
fs.readFile('a.txt', (err, data) => {
if (err) console.error(err); // no return!
console.log(data.length); // crashes: data is undefined
});
The return after handling the error is essential. Without it, execution continues into the success path with undefined data.
Throwing inside a callback
setTimeout(() => {
throw new Error('boom'); // not caught by an outer try/catch
}, 0);
try {
setTimeout(() => { throw new Error('boom'); }, 0);
} catch (e) {
// never runs — the throw happens after the try block has exited
}
A try/catch cannot span an asynchronous boundary. The throw happens in a later task, where the original try block is long gone. This is why error-first callbacks exist.
Losing this
const obj = {
name: 'Ada',
greet() {
setTimeout(function () {
console.log(this.name); // undefined — this is not obj
}, 0);
},
};
A regular function gets its own this. An arrow function inherits it:
setTimeout(() => console.log(this.name), 0); // works
Running callbacks in sequence and in parallel
When you have a collection and need to run an async operation for each item, the naive approach fails silently.
// Bug: forEach does not wait
items.forEach((item) => {
saveItem(item, (err) => {
if (err) console.error(err);
});
});
console.log('all saved'); // runs before any save completes
forEach ignores the return value, so there is no way to know when the operations finish. The callback-based solutions are explicit counters or a recursive walk.
Sequential with a counter:
function saveAll(items, done) {
let remaining = items.length;
if (remaining === 0) return done(null);
items.forEach((item) => {
saveItem(item, (err) => {
if (err) return done(err);
if (--remaining === 0) done(null);
});
});
}
This runs them all in parallel and calls done when the last one finishes. The --remaining counter is the classic pattern, and it is exactly what Promise.all replaces.
Sequential, one at a time:
function saveSequentially(items, done) {
let index = 0;
function next(err) {
if (err) return done(err);
if (index >= items.length) return done(null);
saveItem(items[index++], next);
}
next();
}
Passing next as the callback makes the recursion implicit: each completion triggers the next item. This is the callback equivalent of await in a loop.
Both patterns are correct, and both are easy to get wrong. The counter version can call done twice if an error occurs after some successes; the sequential version can overflow the stack on very large collections. Promises and async/await exist largely because these bookkeeping patterns were so error-prone.
Practical guidance
- Use
if (err) returnat the top of every error-first callback. - Call the callback exactly once — guard against double invocation.
- Prefer promises or async/await for new sequential async code.
- Keep callbacks for events, streams, and middleware, where they fit naturally.
- Use
promisifyrather than hand-writing promise wrappers. - Never throw inside a callback expecting an outer catch to handle it.
- Use arrow functions when you need the enclosing
this.
For the async patterns built on callbacks, see promises vs async/await and event loop explained. For the higher-order function concept behind them, higher-order functions explained.
Quotable summary
A callback is a function passed as an argument to another function, to be invoked later — synchronously during the call, or asynchronously after the current code finishes. Node’s error-first convention passes an error as the first argument and the result as the second, which is why every callback begins with an error check. Callback hell is the nesting produced by chaining dependent asynchronous operations, and it makes error handling repetitive and control flow hard to follow; promises and async/await flatten it. Callbacks remain the right tool for events, streams, and middleware, where invocation is repeated or event-driven rather than a single completion. The most dangerous pitfall is calling a callback more than once, which breaks code that assumes single invocation.