JavaScript · The language round
What is the difference between Promise.all, allSettled, race and any?
Short answer
all waits for every promise and rejects on the first failure. allSettled waits for all and never rejects. race settles with the first result. any fulfils with the first success.
These combinators answer different concurrency questions. The key differences are whether failures reject the combined promise and whether you need every result or just the first one.
const a = Promise.resolve("a");
const b = Promise.reject(new Error("b failed"));
await Promise.all([a, b]); // rejects with "b failed"
await Promise.allSettled([a, b]);
// [{ status: "fulfilled", value: "a" },
// { status: "rejected", reason: Error("b failed") }]
await Promise.race([a, b]); // "a"
await Promise.any([b, a]); // "a"Which one to use
Promise.allwhen every result is required and one failure should abort the operationPromise.allSettledwhen you want every outcome, including failuresPromise.racewhen the first settled promise should win, including a timeoutPromise.anywhen the first success is enough and failures can be ignored until all fail
Promise.any rejects with an AggregateError only when every input rejects. That error contains the individual reasons.
function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) => {
setTimeout(() => reject(new Error("timeout")), ms);
});
return Promise.race([promise, timeout]);
}race: fail if the work takes too long.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Which combinator rejects on the first failure?
- 2How does `Promise.any` differ from `Promise.race`?
- 3How would you implement a timeout?
- 4When would you use `allSettled`?
Say it in the interview
Promise.all waits for all and rejects as soon as one rejects, so it is for work where every result is required. allSettled waits for all and gives statuses for each, never rejecting. race settles with the first promise to settle, which is useful for timeouts. any fulfils with the first success and rejects with an AggregateError only if all fail.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.