What is a callback?
A callback is a function you pass to another function, to be called later when something finishes. You’ve already used them —.map(), .filter(), and .forEach() all take callbacks.
Callbacks for async operations
Beforefetch, JavaScript used XMLHttpRequest with callbacks. Here’s what async code looked like with callbacks:
The error-first callback pattern
Node.js standardized a pattern: the first argument to a callback is always the error (ornull if no error).
The error-first pattern (
callback(error, result)) is a convention, not a language feature. Node.js APIs follow this pattern, but browser APIs like fetch use Promises instead.Callback hell
The real problem shows up when you need multiple async operations that depend on each other — get a user, then get their orders, then get the order details:- Hard to read
- Hard to debug
- Hard to handle errors properly
- Easy to make mistakes
Where you’ll still see callbacks
Callbacks aren’t dead. You’ll use them for:What’s next?
Promises were invented to solve callback hell. They give async operations a cleaner interface and let you chain operations without nesting.Promises
Handle async operations with a cleaner pattern