Sub topic 8
Running Work Concurrently: all, allSettled, race and any
This chapter assumes you can create promises with new Promise, chain them with then and catch, and follow how a rejection moves down a chain to the nearest catch. The examples use plain then chains. The next chapter shows the same patterns with async/await.
Chaining runs steps one after another. Often the steps don't depend on each other. Loading a user profile, their settings and their notifications are three separate requests, and waiting for each one in turn wastes time. JavaScript has four static methods, called combinators, that take several promises and return one promise describing them as a group. The difference between them is how they decide when the group is done and what it settles with.
Concurrency Starts When You Create the Promise
A combinator does not start any work. The work starts when the promise is created, for example when you call fetch(url) or delay(100). The combinator only watches promises that already exist and are already running. The four methods therefore differ only in how they combine results.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const start = Date.now();
Promise.all([delay(300, 'slow'), delay(100, 'fast'), 42]).then((values) => {
console.log(values); // [ 'slow', 'fast', 42 ]
console.log(`took about ${Date.now() - start} ms`); // about 300, not 400
});The whole group takes about as long as the slowest member. The result array keeps input order, not completion order, so 'slow' comes first even though it finished last. Plain values such as 42 are allowed. Each input goes through Promise.resolve, so a non-promise counts as already fulfilled.
Promise.all: Everything or Nothing
Promise.all fulfills with an array of every value once all inputs fulfill. If any input rejects, it rejects right away with that input's reason. This behavior is called fail-fast.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const failAfter = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
Promise.all([
delay(200, 'a').then((v) => {
console.log('a still finished');
return v;
}),
failAfter(50, 'b failed'),
])
.then((values) => console.log('values:', values))
.catch((err) => console.log('all rejected:', err.message));
// all rejected: b failed (at about 50 ms)
// a still finished (at about 200 ms)Two details matter here:
- Nothing is cancelled. The other inputs keep running after the group rejects, and their results are thrown away. Promises have no built-in cancellation. If the work is a network request, you need an
AbortControllerto actually stop it. - Later rejections are swallowed. After the first rejection,
Promise.allhas already attached handlers to every input, so a second failure does not cause an unhandled rejection warning. The trade-off is that you never learn about that second failure.
Use Promise.all when you need every result to continue and one failure makes the whole operation useless. Rendering a page that needs both the user and their permissions is an example.
Promise.allSettled: Report on Everyone
Promise.allSettled waits until every input has settled, whatever the outcome. It always fulfills, never rejects, with an array of result objects in input order:
{ status: 'fulfilled', value }for successes{ status: 'rejected', reason }for failures
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const failAfter = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
const tasks = [delay(100, 'report.pdf'), failAfter(50, 'disk full'), delay(80, 'photo.jpg')];
Promise.allSettled(tasks).then((results) => {
const saved = results
.filter((r) => r.status === 'fulfilled')
.map((r) => r.value);
const errors = results
.filter((r) => r.status === 'rejected')
.map((r) => r.reason.message);
console.log('saved:', saved); // saved: [ 'report.pdf', 'photo.jpg' ]
console.log('errors:', errors); // errors: [ 'disk full' ]
});Use it when the tasks are independent and partial success is useful, such as uploading a batch of files, sending notifications or warming several caches. Because the returned promise never rejects, a catch placed straight after it will never run for task failures. You have to inspect status yourself.
Promise.race: 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));
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));
}
withTimeout(delay(50, 'fast data'), 100).then(
(v) => console.log('ok:', v), // ok: fast data
(err) => console.log(err.message)
);
withTimeout(delay(500, 'slow data'), 100).then(
(v) => console.log('ok:', v),
(err) => console.log(err.message) // Timed out after 100 ms
);The finally clears the timer. Without it, every successful call leaves a pending timer behind, and in Node.js that timer keeps the process alive until it fires. When the timeout wins, the slow promise still runs to completion in the background, because race does not cancel it either.
Promise.any: First Success Wins
Promise.any fulfills with the first input that fulfills and ignores rejections while at least one input might still succeed. It rejects only when every input has rejected. The rejection is an AggregateError, and its errors property holds every reason in input order.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const failAfter = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
Promise.any([failAfter(10, 'mirror 1 down'), delay(60, 'mirror 2 data')])
.then((v) => console.log('got:', v)); // got: mirror 2 data
Promise.any([failAfter(10, 'mirror 1 down'), failAfter(20, 'mirror 2 down')])
.catch((err) => {
console.log(err instanceof AggregateError); // true
console.log(err.errors.map((e) => e.message)); // [ 'mirror 1 down', 'mirror 2 down' ]
});Use it for redundancy, such as querying several mirrors or replicas and taking whichever answers first. Promise.any requires ES2021 (Node.js 15+). Promise.allSettled requires ES2020 (Node.js 12.9+).
Choosing a Combinator
| Method | Fulfills when | Fulfills with | Rejects when | Rejects with | Empty input |
|---|---|---|---|---|---|
| `Promise.all` | all fulfill | array of values | any one rejects | first reason | fulfills with `[]` |
| `Promise.allSettled` | all settle | array of status objects | never (for task failures) | not applicable | fulfills with `[]` |
| `Promise.race` | first settles by fulfilling | that value | first settles by rejecting | that reason | stays pending forever |
| `Promise.any` | first fulfills | that value | all reject | `AggregateError` | rejects with `AggregateError` |
The empty-input column matters when the array is built dynamically. Promise.race([]) never settles, so code waiting on it hangs without any error. Check for an empty array before calling race on a computed list.
Common Errors
Passing promises as separate arguments. Promise.all(p1, p2) does not throw. It returns a promise that rejects with a TypeError, because p1 is not iterable. Always pass one array or other iterable.
Forgetting to return inside map. A block-bodied arrow function without a return produces an array of undefined, which Promise.all treats as values that are already fulfilled:
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const ids = [1, 2, 3];
Promise.all(ids.map((id) => { delay(50, id * 10); })) // bug: no return
.then((v) => console.log(v)); // [ undefined, undefined, undefined ], immediately
Promise.all(ids.map((id) => delay(50, id * 10)))
.then((v) => console.log(v)); // [ 10, 20, 30 ], after about 50 msPassing functions instead of promises. Promise.all([loadUser, loadPosts]) fulfills with the two functions themselves, because a function is a plain value. Call them first: Promise.all([loadUser(), loadPosts()]).
Starting too much at once. Promise.all(urls.map(fetch)) with 10,000 URLs starts 10,000 requests at the same moment. The combinators do not limit concurrency. A simple fix is to run fixed-size batches one after another:
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
function inBatches(items, size, worker) {
const results = [];
let chain = Promise.resolve();
for (let i = 0; i < items.length; i += size) {
const batch = items.slice(i, i + size);
chain = chain
.then(() => Promise.all(batch.map(worker)))
.then((batchResults) => {
results.push(...batchResults);
});
}
return chain.then(() => results);
}
inBatches([1, 2, 3, 4, 5], 2, (n) => delay(100, n * 10))
.then((r) => console.log(r)); // [ 10, 20, 30, 40, 50 ] after about 300 msThe worker is called only inside the then callback, so each batch begins after the previous batch finishes. If worker were called up front, every task would start immediately and batching would have no effect. Batching leaves slots idle while the slowest task in a batch finishes. A worker pool that starts a new task as soon as one finishes uses the slots better, at the cost of more code.
Exercise
You call Promise.all([a, b, c]). Promise b rejects at 20 ms, c rejects at 40 ms, and a fulfills at 100 ms. When does the returned promise settle, with what, and what happens to a and c?
Show answer
It rejects at about 20 ms with b's reason. a keeps running and fulfills at 100 ms, but its value is discarded. c's rejection at 40 ms is ignored and does not trigger an unhandled rejection warning, because Promise.all has already attached handlers to every input.
Exercise
A dashboard loads five independent widgets. A broken widget should show an error box while the other widgets still render. Which combinator fits, and why is Promise.all the wrong choice?
Show answer
Promise.allSettled. It waits for all five and reports each outcome, so you can render the successes and show error boxes for the failures. Promise.all would reject as soon as one widget failed, and you would lose the results of the widgets that loaded.
Exercise
What does Promise.race([]) do, and what does Promise.any([]) do?
Show answer
Promise.race([]) returns a promise that stays pending forever, because no input will ever settle it. Promise.any([]) rejects immediately with an AggregateError whose errors array is empty, because no input can ever fulfill.
Exercise
Write a function firstSuccessOrTimeout(promises, ms) that fulfills with the first fulfilled value among promises, but rejects with an Error "Timed out" if no promise fulfills within ms milliseconds.
Show answer
Combine any and race: function firstSuccessOrTimeout(promises, ms) { let t; const timeout = new Promise((_, reject) => { t = setTimeout(() => reject(new Error('Timed out')), ms); }); return Promise.race([Promise.any(promises), timeout]).finally(() => clearTimeout(t)); }. Promise.any ignores individual failures, and race ends the wait when the timer fires. If every promise fails before the timer fires, the result rejects with the AggregateError.