Sub topic 2
Chaining: Returning Values and Promises from then
This chapter assumes you know how to create a promise and attach then, catch and finally handlers. It also assumes you are comfortable with arrow functions and setTimeout.
Chaining: Returning Values and Promises from then
Every call to then returns a new promise, and that new promise settles with whatever its handler returns. If the handler returns a plain value, the next then receives that value. If it returns a promise, the chain waits for that promise and passes its result along.
Promise.resolve(2)
.then((n) => n * 3)
.then((n) => new Promise((resolve) => setTimeout(() => resolve(n + 1), 50)))
.then((n) => console.log(n)); // 7The most common bug is a handler that starts async work but does not return it. The next step then gets undefined and runs too early.
How Errors Travel Through a Chain
A thrown error or a rejected promise skips every then handler that follows it, until a catch picks it up. Whatever catch returns fulfills the next promise, so the chain carries on as normal. If you want to log an error and still fail, rethrow it inside catch. Use finally for cleanup. It runs whether the chain fulfilled or rejected, and it passes the original result through unchanged.
Promise.resolve()
.then(() => {
throw new Error('boom');
})
.then(() => console.log('skipped'))
.catch((err) => {
console.log('caught:', err.message); // caught: boom
return 'recovered';
})
.then((v) => console.log(v)) // recovered
.finally(() => console.log('cleanup')); // cleanupRunning Work Concurrently: all, allSettled, race and any
The static combinators each take an iterable of promises and return one promise.
| Method | Fulfills when | Rejects when |
|---|---|---|
| `Promise.all` | all fulfill (array of values) | the first one rejects |
| `Promise.allSettled` | all settle (array of `{status, ...}`) | never |
| `Promise.race` | the first to settle fulfills | the first to settle rejects |
| `Promise.any` | the first one fulfills | all reject (`AggregateError`) |
const ok = Promise.resolve(1);
const fail = Promise.reject(new Error('nope'));
Promise.all([ok, fail])
.catch((err) => console.log('all:', err.message)); // all: nope
Promise.allSettled([ok, fail])
.then((results) => console.log(results.map((r) => r.status))); // ['fulfilled', 'rejected']
Promise.any([fail, ok])
.then((v) => console.log('any:', v)); // any: 1Use all when every result is required, allSettled when partial success is fine, race for timeouts, and any for fallback sources.
Exercise
In a chain, a then handler calls fetchUser() (which returns a promise) but has no return statement. What does the next then receive, and when does it run?
Show answer
It receives undefined and runs right away, without waiting for fetchUser() to settle. Any rejection from fetchUser() also escapes the chain's catch.
Exercise
You load three optional widgets and want to render whichever ones succeed. Which combinator fits?
Show answer
Promise.allSettled, because it never rejects and reports each outcome, so you can render the widgets whose status is 'fulfilled'.