all, allSettled, race and any
Four static methods take an array of promises and combine them, and choosing between them is a question about what failure should mean.
all fulfils with every value or rejects on the first failure. allSettled always fulfils, describing each outcome. race settles with the first to finish either way. any takes the first success and ignores failures.
EXERCISE
1all and allSettled: Waiting for Everything
Both wait for the whole list, and they differ entirely in what happens when one of them fails.
Promise.all gives you every value, in order:
const [user, posts, settings] = await Promise.all([
fetch("/api/user").then((r) => r.json()),
fetch("/api/posts").then((r) => r.json()),
fetch("/api/settings").then((r) => r.json()),
]);
Three requests start together and the results come back in the order they were listed, not the order they finished. That ordering guarantee is what makes destructuring safe.
It is also genuinely concurrent, which is the main reason to use it:
// Sequential: each await waits for the previous one. ~900ms total.
const a = await slow(300);
const b = await slow(300);
const c = await slow(300);
// Concurrent: all three start at once. ~300ms total.
const [a2, b2, c2] = await Promise.all([slow(300), slow(300), slow(300)]);
But one rejection rejects the whole thing:
const results = await Promise.all([
Promise.resolve("ok"),
Promise.reject(new Error("failed")),
Promise.resolve("also ok"),
]);
// throws immediately: Error: failed
// The two successful values are lost.
This is called fail-fast, and it is correct when you need all of it or none of it. It is wrong when you want whatever you can get.
Promise.allSettled never rejects:
const results = await Promise.allSettled([
Promise.resolve("ok"),
Promise.reject(new Error("failed")),
Promise.resolve("also ok"),
]);
console.log(results);
// [
// { status: 'fulfilled', value: 'ok' },
// { status: 'rejected', reason: Error: failed },
// { status: 'fulfilled', value: 'also ok' }
// ]
Every entry is described rather than thrown. You then decide what to do:
const succeeded = results
.filter((r) => r.status === "fulfilled")
.map((r) => r.value);
const failed = results.filter((r) => r.status === "rejected");
console.log(`${succeeded.length} ok, ${failed.length} failed`);
The difference is not really about errors. It is about whether a partial result is useful to you. A page that needs a user, their posts and their settings cannot render with two of the three, so failing fast is correct and simpler. A dashboard of six independent widgets absolutely can render with five, and failing the whole page because one widget's endpoint is down would be a worse outcome than showing five.
Choosing between them:
// Rendering a page that needs all three pieces? -> all
// Uploading ten files and reporting per file? -> allSettled
// Loading optional widgets on a dashboard? -> allSettled
Promise.all is about first and combination second. If three awaits in a row do not depend on each other, they are costing you the sum of their times for no reason. Look for consecutive awaits with no data flowing between them; that pattern is the most common easy performance win in async code.
EXERCISE
2race and any: Taking the First
Both settle as soon as one promise does, and they disagree about whether a failure counts as finishing.
Promise.race settles with the first to finish, success or failure:
const winner = await Promise.race([
slow(500).then(() => "slow"),
slow(100).then(() => "fast"),
]);
console.log(winner); // fast
A rejection counts as finishing:
await Promise.race([
slow(500).then(() => "slow"),
Promise.reject(new Error("instant failure")),
]);
// throws: instant failure
Which makes it the standard way to add a timeout:
function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) => {
setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms);
});
return Promise.race([promise, timeout]);
}
const user = await withTimeout(fetch("/api/user"), 3000);
Whichever finishes first wins. If the fetch is slower than three seconds, the timeout rejects and you get a clear error instead of an indefinite wait.
One caveat worth knowing: the losing promise is not cancelled. The fetch keeps going and its result is discarded. For real cancellation you need AbortController, which is beyond this unit, but the distinction matters when the losing work has side effects.
Promise.any takes the first success and ignores failures:
const fastest = await Promise.any([
fetch("https://eu.example.com/data"),
fetch("https://us.example.com/data"),
fetch("https://ap.example.com/data"),
]);
The first mirror to respond wins. A failure does not end it; any keeps waiting for one that works.
It only rejects if every promise rejects, and then with a special error:
try {
await Promise.any([
Promise.reject(new Error("a")),
Promise.reject(new Error("b")),
]);
} catch (err) {
console.log(err.constructor.name); // AggregateError
console.log(err.errors.length); // 2
}
AggregateError carries an errors array holding every individual reason, so nothing is lost.
The four, side by side:
// all every value, or the first rejection -> need all of them
// allSettled a description of every outcome, never rejects -> want a report
// race the first to settle, either way -> timeouts
// any the first to succeed -> fallbacks and mirrors
All four accept any iterable, not only arrays, and all four run their promises concurrently.
Pro Tip: Pick by finishing the sentence "I want...". All of them, or nothing:
all. A report on each:allSettled. Whatever happens first:race. The first one that works:any. That question picks correctly every time, and it is a better guide than remembering four names.
EXERCISE
3Running Many, but Not All at Once
Passing two thousand promises to Promise.all starts two thousand operations at the same moment, which is rarely what you want.
Promise.all has no concept of a limit. Every promise in the array has already started before all ever sees it, because creating a promise starts the work.
Which means this is a problem, not a solution:
const urls = [...]; // two thousand of them
const results = await Promise.all(urls.map((u) => fetch(u)));
Two thousand requests leave at once. Browsers cap concurrent connections per host at around six and queue the rest, so most of them sit waiting anyway. A may rate-limit you, or simply fall over. And memory holds two thousand pending responses.
A pool that keeps a fixed number in flight:
async function pool(items, worker, limit = 5) {
const results = [];
let index = 0;
async function run() {
while (index < items.length) {
const current = index;
index += 1;
results[current] = await worker(items[current]);
}
}
const runners = Array.from({ length: limit }, () => run());
await Promise.all(runners);
return results;
}
const pages = await pool(urls, (u) => fetch(u).then((r) => r.text()), 5);
Five runners share one index. Each takes the next item, waits for it, and loops. When the list is exhausted the runners finish, and Promise.all on the runners waits for all five. Results land at their original positions, so order is preserved.
Sequential when order of execution matters:
const results = [];
for (const item of items) {
results.push(await process(item)); // strictly one at a time
}
A plain for...of with an await inside is genuinely sequential. Use it when each step depends on the last, or when the operations must not overlap, such as writes to the same record.
The shape to avoid is forEach with an async callback:
// Does NOT wait. forEach ignores the returned promise.
items.forEach(async (item) => {
await process(item);
});
console.log("done"); // prints before any processing finishes
forEach was written before promises existed and discards its callback's return value, so there is nothing to await. Unit 6 comes back to this.
Pro Tip: Three shapes cover nearly everything.
Promise.allwhen the list is small and bounded, a pool when it is large or hits a rate limit, and afor...ofloop when the steps genuinely must happen in order. Reaching forPromise.allon an unbounded list is the mistake, and it usually appears as a server that works in testing and fails on real data.
