Careeroza
Promise Combinators
all, allSettled, race, any
| Method | Resolves when | Rejects when |
|---|---|---|
Promise.all | all fulfil (array of values) | any one rejects |
Promise.allSettled | all have settled (never rejects) | — |
Promise.race | the first one settles (fulfils) | the first one settles (rejects) |
Promise.any | the first one fulfils | all reject (AggregateError) |
Example
Example
const ok = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
const fail = (ms, msg) => new Promise((_, j) => setTimeout(() => j(new Error(msg)), ms));
(async () => {
console.log(await Promise.all([ok(20, "A"), ok(10, "B")]));
const settled = await Promise.allSettled([ok(10, "A"), fail(5, "B failed")]);
console.log(settled.map((s) => s.status));
console.log(await Promise.race([ok(30, "slow"), ok(10, "fast")]));
console.log(await Promise.any([fail(5, "x"), ok(20, "first success")]));
try { await Promise.all([ok(10, "A"), fail(5, "B failed")]); }
catch (e) { console.log("all rejected:", e.message); }
})();Output
[ 'A', 'B' ] [ 'fulfilled', 'rejected' ] fast first success all rejected: B failed
A Timeout Wrapper
Example
Use Promise.race to give up on slow operations:
const withTimeout = (promise, ms) =>
Promise.race([promise, new Promise((_, rej) => setTimeout(() => rej(new Error("Timed out after " + ms + " ms")), ms))]);
const slow = new Promise((r) => setTimeout(() => r("done"), 200));
withTimeout(slow, 50).then(console.log).catch((e) => console.log(e.message));Output
Timed out after 50 ms