Sub topic 7
Combining Promises: all, allSettled, race, and any
This chapter assumes you can create Promises, chain them with then and catch, and use await inside an async function. It covers the four built-in combinators. A combinator is a static method that takes an iterable of Promises and returns a single Promise. Each one decides differently when that single Promise settles and what value it carries.
The four combinators at a glance
| Method | Fulfills when | Rejects when | Fulfillment value |
|---|---|---|---|
| `Promise.all` | every input fulfills | any input rejects (first one) | array of values, in input order |
| `Promise.allSettled` | every input settles | never | array of `{ status, value }` or `{ status, reason }` objects |
| `Promise.race` | the first input to settle fulfills | the first input to settle rejects | that first value |
| `Promise.any` | any input fulfills (first one) | every input rejects | that first fulfilled value |
Results from all and allSettled always match the input order, not the order in which the Promises finished.
Promise.all: everything must succeed
Use Promise.all when you need every result and one failure makes the whole job pointless. A page that needs both a user record and its settings is a typical case.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function loadPage() {
const [user, settings] = await Promise.all([
delay(300, { name: 'Ada' }),
delay(100, { theme: 'dark' })
]);
console.log(user.name, settings.theme); // Ada dark
}
loadPage();When one input rejects, Promise.all rejects right away with that reason. The other operations keep running, because a combinator cannot stop work that has already started, but their results are thrown away.
Promise.allSettled: collect every outcome
Use Promise.allSettled when the inputs are independent and you want to report on each one, for example when sending a batch of notifications. It never rejects, so you check each result's status.
async function loadAll() {
const results = await Promise.allSettled([
Promise.resolve('ok'),
Promise.reject(new Error('failed'))
]);
for (const r of results) {
if (r.status === 'fulfilled') {
console.log('value:', r.value);
} else {
console.log('reason:', r.reason.message);
}
}
}
loadAll(); // value: ok, then reason: failedPromise.race: the first to settle wins
Promise.race settles the same way as whichever input settles first, whether that input fulfills or rejects. Its most common use is a timeout.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const timeout = ms =>
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms));
async function withTimeout() {
try {
const result = await Promise.race([delay(2000, 'slow data'), timeout(500)]);
console.log(result);
} catch (err) {
console.log(err.message); // Timed out after 500 ms
}
}
withTimeout();The slow operation still runs to completion in the background. A later chapter shows how to actually cancel it with AbortController.
Promise.any: the first success wins
Promise.any ignores rejections until one input fulfills. Use it when several sources can give the same answer, such as mirror servers. If every input rejects, it rejects with an AggregateError whose errors array lists every reason.
async function firstMirror() {
try {
const value = await Promise.any([
Promise.reject(new Error('mirror A down')),
new Promise(resolve => setTimeout(() => resolve('mirror B'), 200))
]);
console.log(value); // mirror B
} catch (err) {
console.log(err.errors.map(e => e.message));
}
}
firstMirror();Choosing a combinator
Common errors
- Expecting
allto cancel the other operations. It only stops waiting for them. They keep running. - Calling
Promise.race([]). An empty race never settles, so code awaiting it hangs forever.Promise.all([])fulfills immediately with[], andPromise.any([])rejects with anAggregateError. - Reading
r.valueon everyallSettledresult. Rejected entries have areasonproperty and novalue. - Catching the wrong error type from
any. The individual reasons are inerr.errors, not onerritself.
Exercise
You query three weather APIs that return the same data and want the first successful response. If all three fail, you want to log each failure. Which combinator do you use, and where do the individual errors appear?
Show answer
Use Promise.any. It fulfills with the first successful response and skips rejections. If all three reject, it rejects with an AggregateError, and the individual errors are in its errors array.
Exercise
What does await Promise.all([delay(100, 'a'), Promise.reject(new Error('x')), delay(50, 'c')]) do?
Show answer
It rejects at once with Error('x'), so the await throws that error. The two delay timers still fire, but their values are discarded.