Sub topic 8
Running Work Concurrently: all, allSettled, race and any
This chapter assumes you can create promises, consume them with then and catch, and follow how a rejection travels down a chain. Everything here builds on those skills.
Often you have several independent asynchronous tasks, such as fetching three files or calling two services. Running them one after another wastes time. The static combinators Promise.all, Promise.allSettled, Promise.race and Promise.any each take an iterable of promises and return a single promise. That promise settles according to a rule that differs for each combinator.
The four rules
| Combinator | Fulfills when | Rejects when | Fulfillment value |
|---|---|---|---|
| `Promise.all` | every input fulfills | any input rejects (the first one to do so) | array of values, in input order |
| `Promise.allSettled` | every input settles | never | array of `{ status, value }` or `{ status, reason }` |
| `Promise.race` | the first input to settle fulfills | the first input to settle rejects | that first value |
| `Promise.any` | any input fulfills (the first one to do so) | every input rejects | that first value; the rejection is an `AggregateError` |
Here are three of them side by side:
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: 1The results from Promise.all keep input order regardless of which promise finished first. That means you can destructure them safely: const [user, posts] = await Promise.all([...]).
Choosing a combinator
Typical uses:
all: loading several resources that a page needs together.allSettled: batch jobs where you report which items failed.any: querying redundant mirrors and taking the first good answer.race: putting a timeout on an operation.
race as a timeout
const delay = (ms, v) => new Promise((resolve) => setTimeout(() => resolve(v), ms));
const timeout = (ms) =>
new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), ms));
Promise.race([delay(200, 'slow result'), timeout(100)])
.then((v) => console.log('race:', v))
.catch((err) => console.log('race:', err.message)); // race: timeoutThe slow delay keeps running after the race is lost. Its result is simply ignored.
When any fails completely
Promise.any rejects only when every input rejects. It rejects with an AggregateError, whose errors array holds each reason in input order:
Promise.any([Promise.reject(new Error('a')), Promise.reject(new Error('b'))])
.catch((err) => console.log(err.name, err.errors.map((e) => e.message))); // AggregateError ['a', 'b']Common errors
- Expecting
allto wait for the others after a failure. It rejects immediately. The other promises keep running, but their results are lost. UseallSettledif you need them. - Empty inputs.
Promise.all([])andPromise.allSettled([])fulfill with[].Promise.any([])rejects with anAggregateError.Promise.race([])stays pending forever. - Passing functions instead of promises.
Promise.all([fetchA, fetchB])fulfills with the two functions themselves. Call them:Promise.all([fetchA(), fetchB()]). - Non-promise values. These are treated as already fulfilled, so
Promise.all([1, delay(10, 2)])fulfills with[1, 2].
Exercise
Three mirror servers return promises p1, p2 and p3. p1 rejects after 50 ms, p2 fulfills with "B" after 80 ms, and p3 fulfills with "C" after 30 ms. What do Promise.race, Promise.any and Promise.all each settle with?
Show answer
Promise.race fulfills with "C" because p3 settles first, at 30 ms. Promise.any also fulfills with "C", the first fulfillment. Promise.all rejects at 50 ms with p1's error, because one input rejected.
Exercise
You must upload 20 files and then show which ones failed, without stopping at the first failure. Which combinator do you use, and how do you get the failed indexes?
Show answer
Use Promise.allSettled. Then run results.flatMap((r, i) => (r.status === 'rejected' ? [i] : [])) to collect the indexes whose status is "rejected".