Sub topic 1
Why Promises Exist: The Trouble with Nested Callbacks
Before promises, JavaScript ran asynchronous work in one way. You passed a function, called a callback, and some code called it when the work finished. That model still runs underneath timers, file reads and network requests. Writing whole programs with it caused several kinds of bugs that kept coming back. This chapter goes through those problems one at a time, so that each feature of promises in later chapters has a clear reason for being there.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, closures and arrow functions
- Arrays and objects, including
forEachandreduce - The basic idea of a callback and how
setTimeoutschedules work for later - Running scripts in Node.js. Some examples use Node-only features such as
process.on.
You do not need to know anything about promises yet.
The callback contract
A callback API is a function that accepts another function and promises, informally, to call it later. Node.js made one convention standard, the error-first callback: the first argument is an error (or null), and the remaining arguments are the results.
function getUser(id, cb) {
setTimeout(() => {
if (id <= 0) cb(new Error('invalid user id'));
else cb(null, { id, name: 'Ada' });
}, 50);
}
getUser(1, (err, user) => {
if (err) {
console.error('failed:', err.message);
return;
}
console.log('got', user.name); // got Ada
});For one step this works well. The trouble starts when one step's result feeds the next.
Problem 1: Nesting grows sideways
Suppose a checkout has three dependent steps. It loads the user, loads that user's orders, then asks for a shipping quote based on the orders. Each step needs the previous result, so each callback has to sit inside the one before it.
function getUser(id, cb) {
setTimeout(() => {
if (id <= 0) cb(new Error('invalid user id'));
else cb(null, { id, name: 'Ada' });
}, 50);
}
function getOrders(user, cb) {
setTimeout(() => cb(null, [{ total: 20 }, { total: 35 }]), 50);
}
function getShippingQuote(orders, cb) {
setTimeout(() => {
const sum = orders.reduce((s, o) => s + o.total, 0);
cb(null, sum > 50 ? 0 : 5);
}, 50);
}
function checkout(userId, done) {
getUser(userId, (err, user) => {
if (err) return done(err);
getOrders(user, (err, orders) => {
if (err) return done(err);
getShippingQuote(orders, (err, shipping) => {
if (err) return done(err);
const subtotal = orders.reduce((s, o) => s + o.total, 0);
done(null, { name: user.name, total: subtotal + shipping });
});
});
});
}
checkout(1, (err, result) => {
if (err) console.error('failed:', err.message);
else console.log(result);
});
checkout(0, (err, result) => {
if (err) console.error('failed:', err.message);
else console.log(result);
});Running this prints failed: invalid user id first, at about 50 ms, and then { name: 'Ada', total: 55 } at about 150 ms. The output order differs from the call order. That is normal for asynchronous code, and it surprises people reading callback-heavy programs.
Look at the shape of checkout. Every new step adds a level of indentation, and the code drifts rightward into what people call the "pyramid of doom" or "callback hell". The depth itself is a cosmetic problem. The real costs sit underneath it:
- Repeated error checks. Every level has its own
if (err) return done(err);. If you forget one, the error is silently dropped and the next step runs withundefined. - Shadowed names. Each level declares its own
err. That works here, but it makes it easy to check the wrong variable in an edited version. - Hard to reorder or extract. Moving a step or inserting a new one means re-nesting everything below it.
- The forgotten
return. If you writedone(err)withoutreturn, execution continues into the success path, anddonecan be called twice.
Problem 2: try/catch cannot see asynchronous errors
In synchronous code, one try/catch around a block catches any exception thrown inside it. Callbacks break this, because the callback runs later on a fresh call stack, after the try block has already finished.
// Node.js
process.on('uncaughtException', (err) => {
console.log('escaped try/catch:', err.message);
});
try {
setTimeout(() => {
throw new Error('late failure');
}, 10);
} catch (err) {
console.log('caught:', err.message); // never runs
}
console.log('try block finished');
// Output:
// try block finished
// escaped try/catch: late failureWithout the uncaughtException handler, this throw would crash the Node.js process. That is why the error-first convention exists: errors have to be passed along by hand as values, because the language's exception mechanism cannot carry them across the asynchronous gap. Each callback author has to remember to wrap risky code and forward the error. Many forget.
Problem 3: Inversion of control
When you pass a callback to someone else's function, you hand them control over your continuation. You are trusting them to:
- Call it at least once
- Call it at most once
- Pass the arguments in the documented order
- Call it asynchronously every time (or synchronously every time, but not a mix)
- Not swallow exceptions your callback throws
Nothing in the language enforces any of these. Here is what happens when a payment library has a retry bug:
function chargeCard(amount, cb) {
// Buggy library: a retry path reports success twice
setTimeout(() => cb(null, 'ok'), 10);
setTimeout(() => cb(null, 'ok'), 20);
}
let shipments = 0;
chargeCard(50, (err) => {
if (err) return console.error(err);
shipments += 1;
console.log('shipping order, count =', shipments);
});
// shipping order, count = 1
// shipping order, count = 2The customer gets two shipments. The defensive fix is a guard you have to write around every callback you hand out:
function once(fn) {
let called = false;
return (...args) => {
if (called) return;
called = true;
fn(...args);
};
}
function chargeCard(amount, cb) {
setTimeout(() => cb(null, 'ok'), 10);
setTimeout(() => cb(null, 'ok'), 20);
}
chargeCard(50, once((err, status) => {
console.log('charged:', status); // printed once
}));A callback that never fires is worse, because nothing happens at all. Detecting it requires a timeout that you also write by hand.
Problem 4: Sometimes-synchronous callbacks
Some callback APIs call back immediately when they have a cached answer and asynchronously otherwise. The Node.js community nicknamed this "releasing Zalgo". It makes ordering unpredictable:
const cache = new Map();
function getConfig(key, cb) {
if (cache.has(key)) return cb(null, cache.get(key)); // synchronous
setTimeout(() => {
cache.set(key, 'value-for-' + key);
cb(null, cache.get(key)); // asynchronous
}, 10);
}
function demo(label) {
let ready = false;
getConfig('db', () => console.log(label, 'callback, ready =', ready));
ready = true;
}
demo('first');
setTimeout(() => demo('second'), 50);
// first callback, ready = true
// second callback, ready = falseThe same calling code sees different state depending on whether the cache was warm. The fix is to always defer, for example with queueMicrotask(() => cb(null, cache.get(key))) or process.nextTick. As with the other problems, only discipline enforces it.
Problem 5: Coordinating parallel work by hand
Running several independent operations at once and waiting for all of them means writing a counter, a results array, and a failure flag:
function fetchPrice(item, cb) {
setTimeout(() => {
if (item === '') cb(new Error('empty item name'));
else cb(null, item.length * 10);
}, Math.random() * 100);
}
function fetchAllPrices(items, done) {
const results = new Array(items.length);
let remaining = items.length;
let finished = false;
if (remaining === 0) {
queueMicrotask(() => done(null, results)); // stay asynchronous
return;
}
items.forEach((item, i) => {
fetchPrice(item, (err, price) => {
if (finished) return; // ignore late arrivals
if (err) {
finished = true;
return done(err);
}
results[i] = price; // keep input order
remaining -= 1;
if (remaining === 0) {
finished = true;
done(null, results);
}
});
});
}
fetchAllPrices(['tea', 'coffee', 'milk'], (err, prices) => {
if (err) console.error(err.message);
else console.log(prices); // [ 30, 60, 40 ]
});Every line of that bookkeeping is a chance for a bug: writing results.push instead of indexing (which breaks the order), forgetting the empty-array case, or calling done once per failure. Variations such as "first one to succeed" or "report every outcome" need their own versions of this code.
What promises change
A promise is an object that stands for the eventual result of an operation. Instead of handing your continuation to the library, the library hands you back an object, and you decide what to attach to it. Each problem above maps to a guarantee:
| Callback problem | Promise guarantee | Covered in |
|---|---|---|
| Called twice or never checked | A promise settles once and its state never changes afterward | What a Promise Is |
| Sometimes synchronous | Handlers always run asynchronously, as microtasks | The Microtask Queue |
| Manual error forwarding at every level | Rejections skip ahead to the nearest `catch` | How Errors Travel Through a Chain |
| Rightward nesting | `then` returns a new promise, so steps chain flat | Chaining |
| try/catch cannot see async errors | `await` inside `try/catch` restores normal exception handling | async/await |
| Hand-written counters for parallel work | `Promise.all`, `allSettled`, `race`, `any` | Running Work Concurrently |
As a preview, here is the same checkout with promise-returning versions of the three steps:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const getUser = (id) =>
wait(50).then(() => {
if (id <= 0) throw new Error('invalid user id');
return { id, name: 'Ada' };
});
const getOrders = (user) => wait(50).then(() => [{ total: 20 }, { total: 35 }]);
const getShippingQuote = (orders) =>
wait(50).then(() => (orders.reduce((s, o) => s + o.total, 0) > 50 ? 0 : 5));
async function checkout(userId) {
const user = await getUser(userId);
const orders = await getOrders(user);
const shipping = await getShippingQuote(orders);
const subtotal = orders.reduce((s, o) => s + o.total, 0);
return { name: user.name, total: subtotal + shipping };
}
checkout(1).then(console.log).catch((err) => console.error('failed:', err.message));
checkout(0).then(console.log).catch((err) => console.error('failed:', err.message));There is one error handler per call, no nesting, and no repeated if (err). The rest of this tutorial explains how each part of this code works.
Exercises
Exercise
In the nested checkout function, what goes wrong if the line inside the getOrders callback is written as if (err) done(err); without return, and getOrders fails?
Show answer
After calling done(err), execution falls through to getShippingQuote(orders, ...) with orders undefined. orders.reduce then throws a TypeError inside a timer callback, which no caller's try/catch can catch, so the process crashes or done may be called a second time. The return is what stops the success path from running.
Exercise
Why does the try/catch around setTimeout fail to catch the error thrown inside the timer callback?
Show answer
setTimeout only schedules the callback and returns right away, so the try block finishes before the callback runs. When the callback later throws, it runs on a new call stack started by the event loop, and the original try/catch is no longer on that stack.
Exercise
In fetchAllPrices, what bug would appear if results[i] = price were replaced with results.push(price)?
Show answer
The prices would be stored in the order the requests finished rather than the order of the input array. Because fetchPrice uses random delays, ['tea', 'coffee', 'milk'] could produce [40, 30, 60], and the caller could no longer tell which price belongs to which item. Also, results starts as an array of length 3, so push would add entries after three empty slots.
Exercise
List two of the five inversion-of-control trust issues that the once helper does not solve.
Show answer
Any two of these: it cannot make a callback that is never called fire at all; it cannot make the library pass arguments in the correct order; it cannot make a sometimes-synchronous API consistently asynchronous; it cannot stop the library from swallowing exceptions your callback throws. It only enforces "at most once".