dev3 ·
I keep mixing up the four Promise combinators. When should I use each, and what do they return when something fails?
0
DEV3 Developer Forum
Every post is reviewed first. Usually reviewed within 24 hours.
I keep mixing up the four Promise combinators. When should I use each, and what do they return when something fails?
All four take an iterable of promises and return a new promise.
| Method | Resolves when | Rejects when | Result |
|---|---|---|---|
Promise.all |
all fulfil | the first rejects | array of values (input order) |
Promise.allSettled |
all settle | never | array of {status, value/reason} |
Promise.race |
the first settles | the first settles with a rejection | that value or reason |
Promise.any |
the first fulfils | all reject | first value (AggregateError if all fail) |
// all: need every result, fail fast
const [user, posts] = await Promise.all([getUser(), getPosts()]);
// allSettled: want a report, partial success is fine
const res = await Promise.allSettled(urls.map((u) => fetch(u)));
const ok = res.filter((r) => r.status === 'fulfilled').map((r) => r.value);
// race: timeout pattern
const timeout = new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), 5000));
const data = await Promise.race([fetchData(), timeout]);
// any: fastest mirror wins
const fastest = await Promise.any([fetch(mirrorA), fetch(mirrorB)]);
AbortController to actually stop requests.Promise.all([]) resolves to []; Promise.any([]) rejects; Promise.race([]) never settles.all and allSettled follows input order, not completion order.Pitfall: a race timeout does not stop the slow operation; it just stops you waiting.