What is the difference between Promise.all, allSettled, race and any?
all waits for every promise and rejects on the first failure. allSettled waits for all and reports each outcome. race settles with the first promise to settle. any fulfills with the first success and rejects only if all fail.
Explain it simply
Think of four ways to book tickets on several apps at once.
- all: "I need every booking to work." Result: an array of values in the original order. One failure rejects the whole thing immediately.
- allSettled: "Tell me what happened with each." Never rejects; gives
{status, value | reason}for each. - race: "Whoever answers first, success or failure, decides."
- any: "First success wins." It rejects with an AggregateError only if every promise fails.
Use all for dependent data, allSettled for independent jobs where you want a report, race for timeouts, and any for fallback mirrors.
Example
const ok = (v, ms) => new Promise((r) => setTimeout(() => r(v), ms));
const bad = (ms) => new Promise((_, rej) => setTimeout(() => rej(new Error("fail")), ms));
Promise.all([ok("a", 10), ok("b", 20)])
.then((r) => console.log(r.join())); // -> a,b
Promise.all([ok("a", 10), bad(5)])
.catch((e) => console.log(e.message)); // -> fail
Promise.allSettled([ok("a", 10), bad(5)])
.then((r) => console.log(r.map((x) => x.status).join())); // -> fulfilled,rejected
Promise.race([ok("slow", 50), ok("fast", 10)])
.then(console.log); // -> fast
Promise.any([bad(5), ok("win", 20)])
.then(console.log); // -> winWhat to say in the interview
"all fails fast on any rejection and keeps result order; allSettled always waits and reports every outcome; race takes the first settled promise, good for timeouts; any takes the first fulfilled one and only rejects with an AggregateError when all reject."
Common mistakes
- Using Promise.all for independent tasks and losing every result because one failed.
- Forgetting that race can resolve with a rejection.