Sub topic 7
Combining Promises: all, allSettled, race, and any
Real programs rarely wait for just one thing. A dashboard might load a user profile, their notifications, and their settings at once. A client might ask three mirror servers for the same file and take whichever answers first. JavaScript has four static methods for these cases: Promise.all, Promise.allSettled, Promise.race, and Promise.any. Each takes a group of Promises and returns one new Promise. They differ in when that Promise settles and what it settles with.
This chapter assumes you can create Promises, chain them with then and catch, write async functions, and handle rejections with try/catch around await. Earlier chapters covered all of these. Timing comparisons between sequential and parallel code come in the next chapter. This one is about what each combinator does.
The shared model
All four combinators follow the same rules:
- They accept any iterable, usually an array. Items that are not Promises (such as
42or'hello') are treated as already-fulfilled Promises. - They return a Promise right away. The input Promises are already running, because a Promise starts its work when it is created, not when someone awaits it.
- They never cancel anything. When a combinator settles early, the other input operations keep running, and their results are simply ignored.
The last rule causes many surprises. "Promise.all rejected" tells you that one operation failed. It does not mean the other operations stopped.
We will use this helper throughout. It returns a Promise that fulfills or rejects after a delay:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));Promise.all: everything must succeed
Promise.all fulfills when every input fulfills. Its value is an array of results in the same order as the inputs, not in the order they finished. It rejects as soon as any input rejects, with that input's reason. This is called fail-fast behavior.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function main() {
const [user, posts, count] = await Promise.all([
delay(300, { name: 'Ada' }),
delay(100, ['post 1', 'post 2']),
7 // plain values are allowed
]);
console.log(user.name, posts.length, count); // Ada 2 7
}
main();The posts finished first, yet they still sit at index 1. You can rely on the order, so destructuring the result is safe.
Use Promise.all when the results depend on each other as a set. If the page cannot render without all three pieces, there is no point waiting for the others once one has failed.
Fail-fast in practice
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function main() {
try {
await Promise.all([
delay(500, 'slow').then(v => { console.log('slow finished anyway'); return v; }),
fail(100, 'quick failure')
]);
} catch (err) {
console.log('caught:', err.message);
}
}
main();
// caught: quick failure (after ~100 ms)
// slow finished anyway (after ~500 ms)The catch runs after about 100 ms, and the slow operation still finishes later. If that operation had side effects, such as writing to a database, those side effects still happen. Use AbortController (covered in a later chapter) to actually stop the work.
Promise.allSettled: report every outcome
Promise.allSettled waits until every input has settled, either way, and never rejects. Its value is an array of result objects in input order:
{ status: 'fulfilled', value: ... }for a success{ status: 'rejected', reason: ... }for a failure
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function sendNotifications() {
const recipients = ['ana', 'ben', 'cho'];
const results = await Promise.allSettled([
delay(100, 'sent to ana'),
fail(150, 'ben has no email'),
delay(50, 'sent to cho')
]);
const failed = results
.map((r, i) => ({ ...r, recipient: recipients[i] }))
.filter(r => r.status === 'rejected');
console.log(`${results.length - failed.length} sent, ${failed.length} failed`);
for (const f of failed) {
console.log(` ${f.recipient}: ${f.reason.message}`);
}
}
sendNotifications();
// 2 sent, 1 failed
// ben: ben has no emailUse it when the operations are independent and partial success is useful: batch jobs, sending notifications, loading optional widgets. Since it never rejects, a try/catch around it will not catch the individual failures. You have to check status yourself. Forgetting to do this is the most common mistake with allSettled, because the failures then disappear without anyone noticing.
Promise.race: the first to settle wins
Promise.race settles the same way as the first input to settle, whether that input fulfills or rejects. Its most common use is a timeout:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
async function main() {
console.log(await withTimeout(delay(100, 'fast result'), 500)); // fast result
try {
await withTimeout(delay(1000, 'slow result'), 300);
} catch (err) {
console.log(err.message); // Timed out after 300 ms
}
}
main();The finally that clears the timer matters. Without it, every successful call leaves a timer pending. In Node.js, a pending timer keeps the process alive until it fires. Remember also that the timeout only stops the waiting. The slow operation keeps running in the background.
Because a rejection can win the race, race is a poor choice for "first successful answer." If the fastest mirror server returns an error, race rejects even when a slower server would have succeeded. That case calls for any.
Promise.any: the first success wins
Promise.any fulfills with the first input that fulfills and ignores rejections, unless every input rejects. In that case it rejects with an AggregateError, whose errors property holds all the reasons in input order.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function main() {
const file = await Promise.any([
fail(50, 'mirror A down'),
delay(200, 'data from mirror B'),
delay(400, 'data from mirror C')
]);
console.log(file); // data from mirror B
try {
await Promise.any([fail(50, 'A down'), fail(80, 'B down')]);
} catch (err) {
console.log(err instanceof AggregateError); // true
console.log(err.errors.map(e => e.message)); // [ 'A down', 'B down' ]
}
}
main();Use any for redundant sources, fallbacks, and "try several strategies and take whichever works." It needs Node.js 15+ or a browser from 2020 or later.
Choosing a combinator
| Combinator | Fulfills when | Fulfills with | Rejects when | Rejects with |
|---|---|---|---|---|
| `Promise.all` | All inputs fulfill | Array of values, input order | Any input rejects | First rejection reason |
| `Promise.allSettled` | All inputs settle | Array of `{status, value/reason}` | Never | Not applicable |
| `Promise.race` | First settled input fulfilled | That value | First settled input rejected | That reason |
| `Promise.any` | Any input fulfills | First fulfilled value | All inputs reject | `AggregateError` |
Edge cases
Empty input
What happens with an empty array follows from each combinator's rule, but some of the results still surprise people:
Promise.all([]).then(v => console.log('all:', v)); // all: []
Promise.allSettled([]).then(v => console.log('allSettled:', v)); // allSettled: []
Promise.any([]).catch(e => console.log('any:', e.constructor.name)); // any: AggregateError
Promise.race([]).then(() => console.log('race settled')); // never logsPromise.race([]) stays pending forever, because no input will ever settle. If you build the input array dynamically, for example from a filtered list of servers, check that it is not empty before you race it. An await on that Promise would hang without any error.
Passing Promises versus functions
Combinators take Promises, not functions that produce Promises. This mistake is easy to make:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const tasks = [() => delay(100, 'a'), () => delay(100, 'b')];
async function main() {
const wrong = await Promise.all(tasks);
console.log(typeof wrong[0]); // function — nothing was run
const right = await Promise.all(tasks.map(task => task()));
console.log(right); // [ 'a', 'b' ]
}
main();The functions count as plain values, so Promise.all fulfills immediately with the functions themselves. To run the tasks, call each function so you have an array of Promises.
Rejections created before the combinator attaches
If you create a Promise, await something else, and only then pass that Promise to a combinator, a rejection in the meantime may be reported as unhandled. Create the Promises and hand them to the combinator in the same synchronous step, usually await Promise.all(items.map(fn)), so a handler is attached before any rejection can happen.
Exercise
You call await Promise.all([fetchProfile(), fetchFeed()]). fetchFeed rejects after 50 ms and fetchProfile fulfills after 300 ms. When does your catch block run, what error does it receive, and does the profile request stop?
Show answer
The catch block runs after about 50 ms and receives fetchFeed's rejection reason. The profile request does not stop. It keeps running and fulfills at about 300 ms, and its value is discarded. Promise.all never cancels its inputs.
Exercise
You have three weather APIs. You want the first successful response, and if all three fail you want to log every failure message. Which combinator do you use, and how do you get at the messages?
Show answer
Use Promise.any. If all three reject, it rejects with an AggregateError. Catch it and read err.errors, an array of the three rejection reasons in input order, for example err.errors.map(e => e.message).
Exercise
A colleague writes const results = await Promise.allSettled(jobs.map(run)) inside try/catch and says failures will be logged by the catch block. What is wrong, and how do you fix it?
Show answer
Promise.allSettled never rejects, so the catch block never runs for job failures. Filter the results for r.status === 'rejected' and log r.reason for each one.
Exercise
Why does await Promise.race(servers.map(ping)) hang forever when servers is an empty array, and how do you guard against it?
Show answer
Promise.race settles only when one of its inputs settles. With no inputs it stays pending forever. Check servers.length before racing and throw an error (or return a default) when it is zero, or add a timeout Promise to the race.