Intermediate · 8 of 17 · 16 min read
Callbacks
A function passed to be called later, the error-first convention, and why callback hell and lost context led to promises.
- Callbacks
A callback is a function you hand to other code so that it can call it. Nothing more. It works because functions are values in JavaScript — they can be stored, passed and returned like a number.
Passing versus calling
The single most common callback bug, in one block:
function greet() {
return 'hello';
}
setTimeout(greet, 100); // correct: greet runs in 100ms
setTimeout(greet(), 100); // wrong: greet runs now, "hello" is scheduled and ignored
The same mistake in a React prop or a DOM listener:
// element.addEventListener('click', handleClick()); // runs once, listens to nothing
// <button onClick={handleClick()}> // runs on every render
// element.addEventListener('click', handleClick); // correct
// <button onClick={handleClick}> // correct
// <button onClick={() => handleClick(id)}> // correct, with an argument
When you need to pass an argument, wrap it in an arrow — the arrow is the callback, and it calls your function with what it needs.
Synchronous callbacks
Not every callback is asynchronous. All the array methods take one, and they run immediately, in order:
const doubled = [1, 2, 3].map((n) => n * 2);
console.log(doubled); // [2, 4, 6] — already done
console.log('before');
[1, 2].forEach((n) => console.log('inside', n));
console.log('after');
// before / inside 1 / inside 2 / after
A callback you write yourself is synchronous unless something makes it otherwise:
function process(value, onDone) {
const result = value * 2;
onDone(result); // called straight away
}
process(5, (r) => console.log('got', r)); // got 10
console.log('next'); // next — after, as written
Asynchronous callbacks
Now the callback is kept and invoked later, after the current synchronous work has finished:
console.log('one');
setTimeout(() => console.log('three'), 0);
console.log('two');
// one / two / three — even with a 0ms delay
This is the ordering that makes callbacks worth understanding: the function runs when the event loop gets to it, which is always after the current script.
A node-style asynchronous API, where the result can only be delivered through the callback:
function fetchUser(id, callback) {
setTimeout(() => {
if (id <= 0) {
callback(new Error('bad id'));
return;
}
callback(null, { id, name: 'Ana' });
}, 50);
}
fetchUser(1, (error, user) => {
if (error) {
console.log('failed:', error.message);
return;
}
console.log('got', user.name); // got Ana
});
The error-first convention
Node’s standard shape, and it is worth recognising even in a promise-based codebase:
| Position | Meaning |
|---|---|
| first argument | the error, or null when there was none |
| later arguments | the result, only meaningful when the error is null |
const handle = (error, data) => {
if (error) return console.log('error:', error.message); // always check first
console.log('data:', data);
};
handle(null, 42); // data: 42
handle(new Error('nope')); // error: nope
A callback cannot throw usefully across an asynchronous boundary — by the time it runs, the
try/catch around the original call is long gone:
function later(cb) {
setTimeout(cb, 0);
}
try {
later(() => {
throw new Error('boom');
});
} catch (error) {
console.log('never reached'); // the stack that had this catch is gone
}
That is exactly why the error travels as a value in the first argument instead.
Callback hell
Each step depends on the one before, so each nests inside it:
getUser(1, (err, user) => {
if (err) return handle(err);
getOrders(user.id, (err, orders) => {
if (err) return handle(err);
getOrderDetails(orders[0].id, (err, details) => {
if (err) return handle(err);
getShipping(details.shipmentId, (err, shipping) => {
if (err) return handle(err);
console.log(shipping); // four levels deep, and the error check is repeated four times
});
});
});
});
Three separate problems, and they are what promises address one by one:
| Problem with callbacks | What promises do |
|---|---|
| Nesting grows with each step | .then chains stay flat |
| Error handling is repeated at every level | one .catch for the whole chain |
| No value to hold, pass or combine | a promise is a value: return it, store it, Promise.all it |
The same work, flat:
getUser(1)
.then((user) => getOrders(user.id))
.then((orders) => getOrderDetails(orders[0].id))
.then((details) => getShipping(details.shipmentId))
.then((shipping) => console.log(shipping))
.catch(handle); // one place for every failure above
And with async/await, which reads like the synchronous version:
async function load() {
try {
const user = await getUser(1);
const orders = await getOrders(user.id);
const details = await getOrderDetails(orders[0].id);
return await getShipping(details.shipmentId);
} catch (error) {
handle(error);
}
}
Promisifying a callback API
The bridge you will actually write when wrapping an older library:
function fetchUser(id, callback) {
setTimeout(() => (id > 0 ? callback(null, { id }) : callback(new Error('bad id'))), 10);
}
const fetchUserAsync = (id) =>
new Promise((resolve, reject) => {
fetchUser(id, (error, user) => (error ? reject(error) : resolve(user)));
});
fetchUserAsync(1).then((u) => console.log(u.id)); // 1
fetchUserAsync(0).catch((e) => console.log(e.message)); // bad id
Node ships this as util.promisify, and most platform APIs already return promises. The pattern is
worth knowing because the adapter is four lines and removes a whole callback layer from a codebase.
Callbacks that are still the right tool
Promises replaced callbacks for a single future result. They did not replace them for repeated events, which is most of the DOM:
// Many values over time — a callback, not a promise:
// element.addEventListener('input', (event) => console.log(event.target.value));
// setInterval(() => console.log('tick'), 1000);
// Synchronous transformation — a callback:
console.log([3, 1, 2].sort((a, b) => a - b)); // [1, 2, 3]
A promise settles once. If the thing can happen many times, the callback is correct.
Keeping this
A method passed as a callback loses its receiver, as always:
const timer = {
seconds: 0,
tick() { this.seconds += 1; return this.seconds; },
};
// setInterval(timer.tick, 1000); // TypeError: `this` is undefined
const bound = timer.tick.bind(timer);
console.log(bound(), bound()); // 1 2
Common mistakes
Calling the callback instead of passing it
Mistake. addEventListener('click', handle()).
Why it fails. The call runs now and its return value — usually undefined — is registered as the
listener.
What to do instead. Pass handle, or () => handle(arg) when an argument is needed.
Returning a value from an asynchronous callback
Mistake. function get() { fetchUser(1, (e, u) => u); } and expecting get() to return the
user.
Why it fails. The outer function returned long before the callback ran, and the callback’s return
value goes to whoever invoked it — not to you.
What to do instead. Return a promise, or take a callback of your own and pass the value onward.
Checking the error last
Mistake. Using data first and testing error afterwards.
Why it fails. On failure data is undefined, so the first line throws before the check runs.
What to do instead. Guard and return at the top: if (error) return handle(error).
Check yourself
One question from the bank on what you just read. Answering here does not affect your quiz history.
What problem do promises solve that plain callbacks do not?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.