Callbacks and Callback Hell
Passing a function to run later — why deeply nested callbacks become the "pyramid of doom," and the error-first convention built to cope with it.
Callbacks and Callback Hell
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A callback is just a function passed as an argument so that something else — a timer, a file read, a network request — can call it once the work is actually done. Before promises existed, this was the *only* pattern for asynchronous JavaScript.
- Callbacks compose badly when one async step depends on the result of the previous one: each new step has to be nested *inside* the previous callback, since that's the only place its result is actually available.
- That nesting is "callback hell" or the "pyramid of doom" — code that drifts further right with every dependent step, where the actual logic gets buried under indentation, and a typo three levels deep is hard to even locate.
- Because a callback runs long after the function that scheduled it has returned, a `try`/`catch` wrapped around the original call can't catch an error thrown inside the callback — by the time it runs, that original stack frame is gone.
- Node's workaround is the error-first callback convention: every callback's first parameter is reserved for an error (`null` if there wasn't one), so failure gets passed as ordinary data instead of thrown, and every caller is expected to check it before touching the rest of the arguments.
The original answer to “do this later”
The previous lesson
covered how the engine hands work off to the host environment and brings
a result back once it’s ready. This lesson is about the oldest way
JavaScript code actually consumes that result: the callback. You pass a
function as an argument, and whoever you handed it to calls it back once
their work is done. setTimeout(callback, 1000), element.addEventListener( "click", callback), fs.readFile(path, callback) — same idea everywhere.
For a long time, this was the entire toolkit for asynchronous JavaScript.
There was no Promise, no async/await; a callback was the only
mechanism available.
For a single async step, this is fine. The trouble starts the moment one async step needs the result of another.
Why dependent steps pile up into a pyramid
Say you need a user’s record, then that user’s orders, then the details of one specific order — and each step is itself asynchronous:
getUser(userId, (err, user) => {
if (err) return handleError(err);
getOrders(user.id, (err, orders) => {
if (err) return handleError(err);
getOrderDetails(orders[0].id, (err, details) => {
if (err) return handleError(err);
console.log(details);
});
});
});
Every step’s result is only reachable inside its own callback, which
means every step that depends on a previous one has no choice but to be
written nested inside it. There’s no way to “flatten” this with callbacks
alone — the nesting isn’t a style choice, it’s forced by where the data
actually becomes available. Add a fourth or fifth dependent step, and the
code keeps drifting right with every one, indentation eating more of the
line than the actual logic. That’s “callback hell,” also called the
“pyramid of doom” for the shape it draws on the page. It’s not just
ugly — error handling has to be repeated at every level by hand (notice
the three near-identical if (err) checks above), and a mistake in one of
them quietly swallows a failure instead of surfacing it.
Why a normal try/catch can’t save you here
A natural instinct is to wrap the whole thing in try/catch and call it
a day. That doesn’t work, and the reason connects straight back to the
event loop: a try/catch only catches a throw that happens while
that stack frame is still active. getUser’s callback doesn’t run until
long after getUser(...) itself has already returned — the call stack
frame that contained your try is gone by then. A throw inside the
callback has nothing above it to catch it.
try {
getUser(userId, (err, user) => {
throw new Error("oops"); // this does NOT get caught below
});
} catch (e) {
// never runs
}
Node’s workaround: push the error into the data
Since you can’t rely on a thrown exception crossing that boundary, Node’s convention is to stop throwing and start returning the error as an ordinary value — specifically, as the callback’s first argument. This is the error-first callback pattern:
fs.readFile("config.json", (err, data) => {
if (err) {
// something went wrong; handle it and stop here
return console.error(err);
}
// only reachable once err is falsy — data is safe to use
console.log(data);
});
err is null when nothing went wrong, and some Error object when
something did. Because this ordering is consistent across nearly every
callback-based Node API, checking err first became a predictable habit
rather than something you have to remember per function. It’s a real
improvement over silent failure — but it’s still manual, repeated at every
single nesting level, which is precisely the gap Promise was designed to
close.
Where this fits
This lesson assumes you’ve already got
the event loop and the call stack:
the reason a try/catch can’t cross a callback boundary only makes
sense once you know the original call’s stack frame is long gone by the
time that callback actually runs. From here, promises
pick up exactly where callback hell leaves off — the same “run this once
that’s done” idea, but as a first-class value you can chain, combine, and
hand a single .catch() instead of repeating error checks at every level.
Check yourself
What exactly is a callback, and why did asynchronous JavaScript rely entirely on them before promises existed?
A callback is a function passed as an argument to another function, specifically so that function can call it later, once some work finishes. Before `Promise` was added to the language, there was no other built-in way to say "run this bit of code once that timer fires / that file finishes loading / that response arrives" — a callback was the only mechanism available for that.
Why does fetching a user, then their orders, then one order's details, end up deeply nested instead of written as three separate steps in a row?
Each step needs data that only exists once the previous step's callback actually runs — you can't ask for a user's orders before you have the user, and you can't call for order details without an order ID. Since a callback's result is only available *inside* that callback, each dependent step has to be written nested inside the one before it, which is exactly what produces the rightward-drifting pyramid shape.
Why can't you just wrap the original call in a normal `try`/`catch` to handle an error that happens inside one of its callbacks?
By the time the callback actually runs, the function call that scheduled it has already returned and its stack frame is gone — the `try`/`catch` around that original call finished executing long before the callback ever fires. A `throw` inside the callback has nothing left to be caught by; it would just become an unhandled error, which is exactly the problem the error-first convention exists to avoid.
In Node's error-first callback convention — `fs.readFile(path, (err, data) => { ... })` — what is the caller supposed to do with `err`, and why does it come first?
Check whether `err` is truthy before touching `data` at all; if it isn't `null`, something went wrong and `data` likely isn't valid or present. It's placed first by convention, consistently, across virtually every Node callback, specifically so error-checking becomes a predictable first line in every callback instead of something easy to forget or bury.
Besides the nesting itself, what makes callback-based code hard to maintain as more async steps get added?
Error handling has to be repeated manually at every single level of nesting, since there's no shared mechanism to let a failure skip straight to one handler — forget a check at any level and that error silently vanishes. Running two independent steps concurrently is also awkward, since the callback pattern only naturally expresses "do this, then when it's done, do that," not "start these two things and tell me when both finish".
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.