Skip to content
  • Promise.all, allSettled, race & any · JavaScript

Promise.all, allSettled, race & any

LearnViaNotes @learnvianotes· 2 min read

Four static methods run many promises concurrently and combine the results — they differ only in when they settle and what counts as failure.

MethodFulfils whenRejects whenResult
Promise.allAll fulfilAny rejects (fail-fast)Array of values, in input order
Promise.allSettledAll settleNeverArray of {status, value \| reason}
Promise.raceThe first to settle fulfilsThe first to settle rejectsThat one value/reason
Promise.anyThe first to fulfilAll rejectValue, or AggregateError
JavaScript
const ok = (ms, v) => new Promise((res) => setTimeout(() => res(v), ms));
const bad = (ms, msg) => new Promise((_, rej) => setTimeout(() => rej(new Error(msg)), ms));

console.log("all:", await Promise.all([ok(30, "a"), ok(10, "b"), 42]));
await Promise.all([ok(10, "a"), bad(5, "db down")]).catch((e) => console.log("all rejected:", e.message));

const settled = await Promise.allSettled([ok(5, "a"), bad(5, "nope")]);
console.log(settled.map((r) => (r.status === "fulfilled" ? r : { ...r, reason: r.reason.message })));

console.log("race:", await Promise.race([ok(20, "slow"), ok(5, "fast")]));
console.log("any:", await Promise.any([bad(5, "x"), ok(15, "first success")]));
try {
  await Promise.any([bad(5, "e1"), bad(5, "e2")]);
} catch (e) {
  console.log(e.constructor.name, e.errors.map((x) => x.message));
}
Output
all: [ 'a', 'b', 42 ]
all rejected: db down
[
  { status: 'fulfilled', value: 'a' },
  { status: 'rejected', reason: 'nope' }
]
race: fast
any: first success
AggregateError [ 'e1', 'e2' ]

Pattern: timeout with race

JavaScript
const timeout = (ms) => new Promise((_, rej) => setTimeout(() => rej(new Error(`timed out after ${ms}ms`)), ms));
const slowFetch = new Promise((res) => setTimeout(() => res("data"), 50));
try {
  await Promise.race([slowFetch, timeout(10)]);
} catch (e) {
  console.log(e.message);
}
Output
timed out after 10ms

Sequential vs parallel

JavaScript
const job = (id, log) => new Promise((res) => setTimeout(() => { log.push(id); res(id); }, 10 * (4 - id)));

const seq = [];
for (const id of [1, 2, 3]) await job(id, seq);          // one after another
console.log("sequential finish order:", seq);

const par = [];
const results = await Promise.all([1, 2, 3].map((id) => job(id, par)));  // all at once
console.log("parallel finish order:", par, "results:", results);
Output
sequential finish order: [ 1, 2, 3 ]
parallel finish order: [ 3, 2, 1 ] results: [ 1, 2, 3 ]

Promise.all vs Promise.allSettled?

race vs any?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report