DEV3 Technologies home

DEV3 Developer Forum

What is the difference between Promise.all, allSettled, race and any?

JavaScript helpSolved0 views
dev3 ·

I keep mixing up the four Promise combinators. When should I use each, and what do they return when something fails?

#javascript#promises

0

1 reply

dev3 · Accepted answer

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)

Examples

// 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)]);

Notes

  • Rejections of the "losing" promises are still handled (no unhandled rejection) when passed to these methods.
  • None of these cancel the other work. Use AbortController to actually stop requests.
  • Promise.all([]) resolves to []; Promise.any([]) rejects; Promise.race([]) never settles.
  • Order of results in all and allSettled follows input order, not completion order.

Pitfall: a race timeout does not stop the slow operation; it just stops you waiting.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.