Sub topic 3
Chaining Promises with then, catch, and finally
This chapter assumes you can create a Promise with new Promise, and that you know a Promise is pending, fulfilled, or rejected. You should also be comfortable with arrow functions and callbacks.
Chaining lets you run asynchronous steps in order without nesting callbacks. Async functions, covered in the next chapter, are built on this same model, so it is worth learning well.
The core rule: then returns a new Promise
Each call to .then() returns a new Promise. What your callback does decides how that new Promise settles:
| Callback does this | The Promise returned by `then` |
|---|---|
| Returns a plain value | Fulfills with that value |
| Returns a Promise | Waits for it, then settles the same way it does |
| Throws an error | Rejects with that error |
| Returns nothing | Fulfills with `undefined` |
Because every step returns a Promise, you can attach the next step straight to it:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
delay(100, 2)
.then(n => n * 10) // plain value: next step gets 20
.then(n => delay(100, n + 1)) // Promise: chain waits 100 ms
.then(n => console.log('result:', n)); // result: 21The second step returns a Promise, so the third step does not run until that Promise fulfills. This lets one async step depend on the result of the step before it.
How rejections travel down the chain
When a step rejects, the chain skips every .then() fulfillment handler until it reaches a .catch(). A .catch() handles a rejection from any step above it. If the catch handler returns a value, the chain recovers and continues as fulfilled.
.finally() runs whether the chain fulfilled or rejected. Its callback receives no argument, which makes it the place for cleanup such as hiding a loading spinner.
Promise.resolve(5)
.then(n => {
if (n > 3) throw new Error('too big');
return n;
})
.then(n => console.log('never runs', n))
.catch(err => {
console.log('caught:', err.message);
return 0; // recover with a fallback value
})
.then(n => console.log('recovered with', n))
.finally(() => console.log('cleanup'));
// caught: too big
// recovered with 0
// cleanupfinally passes the result through
.finally() does not change the value or error that passes through it. Its own return value is ignored:
Promise.resolve('data')
.finally(() => 'ignored')
.then(v => console.log(v)); // dataCommon errors
Forgetting to return
If you start an async operation inside then but do not return it, the chain stops waiting for it. The next step then receives undefined:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
delay(100, 'a')
.then(a => {
delay(100, a + 'b'); // missing return
})
.then(result => console.log(result)); // undefinedYou can fix it by writing return delay(100, a + 'b');, or by using an arrow function with an expression body: a => delay(100, a + 'b').
Nesting instead of chaining
Putting a .then() inside another .then() brings back the callback pyramid. It also breaks error handling, because a .catch() on the outer chain will not see a rejection from an inner chain that was never returned. Return the inner Promise and keep the chain flat.
Putting catch in the wrong place
A .catch() only handles errors from steps above it. If you put it early in the chain, errors thrown by later steps will go unhandled. Usually one .catch() near the end of the chain is enough. Add an earlier one only where you want to recover with a fallback value and keep going.
Exercise
What does this code log, and in what order? Promise.reject(new Error('x')).then(() => console.log('A')).catch(e => { console.log('B', e.message); return 'y'; }).then(v => console.log('C', v)).finally(() => console.log('D'));
Show answer
It logs "B x", then "C y", then "D". The rejection skips the handler that logs A. The catch handler logs B and recovers by returning 'y'. The next then receives 'y' and logs C. Finally runs last and leaves the result unchanged.
Exercise
A chain is written as fetchUser().then(user => { fetchPosts(user.id); }).then(posts => render(posts)); but render always receives undefined. Why, and how do you fix it?
Show answer
The first then callback has a block body with no return statement, so it fulfills with undefined and does not wait for fetchPosts. Return the Promise, either with "return fetchPosts(user.id);" or with the expression form "user => fetchPosts(user.id)".