Sub topic 1
Why Promises Exist: The Trouble with Nested Callbacks
JavaScript runs your code on a single thread, so slow work such as network requests, file reads and timers can't block it. For years the standard way to handle a result that arrives later was a callback: you pass a function, and the API calls it when the work finishes. Callbacks work, but they cause real problems once you chain several steps together. This chapter covers those problems so you can see what promises were designed to fix.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, closures and arrow functions
- Arrays and objects
- The basic idea of callbacks and
setTimeout - Running scripts in Node.js or a browser console
A Three-Step Task with Callbacks
Suppose you need to load a user, then load that user's orders, then compute the total. Each step is asynchronous. The functions below follow the Node.js error-first convention: the callback receives (err, result).
function getUser(id, cb) {
setTimeout(() => cb(null, { id, name: 'Ada' }), 50);
}
function getOrders(user, cb) {
setTimeout(() => cb(null, [{ id: 1, total: 30 }, { id: 2, total: 12 }]), 50);
}
function getTotal(orders, cb) {
setTimeout(() => {
if (orders.length === 0) cb(new Error('No orders'));
else cb(null, orders.reduce((sum, o) => sum + o.total, 0));
}, 50);
}
getUser(7, (err, user) => {
if (err) return console.error('user failed:', err.message);
getOrders(user, (err, orders) => {
if (err) return console.error('orders failed:', err.message);
getTotal(orders, (err, total) => {
if (err) return console.error('total failed:', err.message);
console.log(`${user.name} spent ${total}`); // Ada spent 42
});
});
});The code is correct, but it already shows the problems below.
Problem 1: The Pyramid of Doom
Every dependent step goes one level deeper. With five or six steps the logic drifts to the right and gets hard to follow. This shape is often called "callback hell" or the "pyramid of doom."
Problem 2: Error Handling Repeats at Every Level
Each callback has to check err itself. If you forget one check, the error is silently ignored. You also can't wrap the whole sequence in try/catch, because the callbacks run later, after the try block has already finished:
try {
setTimeout(() => {
throw new Error('too late');
}, 10);
} catch (err) {
console.log('never reached');
}
// The error is uncaught and crashes Node.jsProblem 3: Inversion of Control
When you pass a callback, the other code decides when, whether and how often to call it. A buggy library might call it twice, never call it, or call it synchronously one time and asynchronously the next. Your code has to defend against all of these cases.
function flakyLoad(cb) {
cb(null, 'first');
cb(null, 'second'); // bug: called again
}
flakyLoad((err, value) => console.log('got', value));
// got first
// got secondProblem 4: Composition Is Manual
Running two requests at the same time and waiting for both means writing your own counters and flags. Patterns like "whichever finishes first" or "wait for all, even the failures" each need their own hand-written bookkeeping.
What Promises Change
A promise is an object that stands for the eventual result of an async operation. Instead of handing your callback to someone else, you get back a value that you can attach handlers to.
| Callback problem | How promises address it |
|---|---|
| Deep nesting | Steps chain one after another at the same indentation level |
| Repeated error checks | One `catch` handles failures from any earlier step |
| Called twice or never | A promise settles once and never changes after that |
| Manual coordination | Built-in helpers such as `Promise.all` combine operations |
Later chapters cover each of these in detail, starting with the states a promise moves through.
Exercise
In the three-step example, why can't you remove the three if (err) checks and put a single try/catch around the outer getUser(...) call?
Show answer
The callbacks run later, from the timer queue, after the try/catch block has already finished. Errors passed to or thrown inside those callbacks are outside the try block's reach, so each level has to check its own error.
Exercise
Name one guarantee a promise gives that the flakyLoad callback API does not.
Show answer
A promise settles only once. After it is fulfilled or rejected, its state and value can't change, so its handlers never run twice for one result.