Sub topic 13
Choosing the Right Combinator
This chapter assumes you have read the earlier chapters on Promise.all, Promise.allSettled, Promise.race, and Promise.any. You should be comfortable with async functions, await, and try/catch. Here we stop looking at the combinators one at a time and compare them, so you can pick the right one for a real task and avoid the usual mix-ups.
Two Questions Decide Most Cases
Each of the four combinators answers a different question about a group of promises. Before you write any code, answer these two questions about your task:
- How many results do you need? You might need every result, or just one.
- What should a failure do? A failure might end the whole operation, or it might only be something you record while you carry on.
If you need every result, the choice is between Promise.all and Promise.allSettled. If you need one result, the choice is between Promise.race and Promise.any. The second question then picks the combinator within each pair.
| Combinator | Fulfills when | Rejects when | Fulfillment value | Typical use |
|---|---|---|---|---|
| `Promise.all` | every input fulfills | the first input rejects | array of values in input order | data that must all be present |
| `Promise.allSettled` | every input settles | never (for a valid iterable) | array of `{ status, value }` or `{ status, reason }` | batch jobs, dashboards, reports |
| `Promise.race` | the first input to settle fulfills | the first input to settle rejects | that first value | timeouts, "whichever answers first" |
| `Promise.any` | the first input fulfills | every input rejects | that first value | fallbacks, redundant mirrors |
Same Inputs, Four Different Answers
The clearest way to see the difference is to give all four combinators the same inputs. In the code below, task A rejects after 50 ms, B fulfills after 100 ms, and C fulfills after 150 ms. The inputs function builds fresh promises for each run, so no run affects another.
const ok = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
function inputs() {
return [fail(50, 'A failed'), ok(100, 'B'), ok(150, 'C')];
}
async function report(name, run) {
try {
const result = await run();
console.log(`${name} fulfilled:`, JSON.stringify(result));
} catch (err) {
console.log(`${name} rejected:`, err.message);
}
}
async function main() {
await report('all', () => Promise.all(inputs()));
await report('allSettled', () =>
Promise.allSettled(inputs()).then((rs) => rs.map((r) => r.status))
);
await report('race', () => Promise.race(inputs()));
await report('any', () => Promise.any(inputs()));
}
main();
// all rejected: A failed
// allSettled fulfilled: ["rejected","fulfilled","fulfilled"]
// race rejected: A failed
// any fulfilled: "B"Promise.all and Promise.race both reject with A's error, for different reasons. all rejects because one input failed. race rejects because A was the first input to settle at all. Promise.any skips A's failure and takes B. Promise.allSettled waits the full 150 ms and reports all three outcomes.
Matching Combinators to Real Tasks
Use Promise.all when the pieces only make sense together
Suppose you render a checkout page. It needs the cart, the user's address, and shipping rates. If any one is missing, the page cannot be shown, so failing fast is correct. Promise.all gives you the values in input order, which makes destructuring easy: const [cart, address, rates] = await Promise.all([...]).
The cost is that one failure throws away the successful results, and the other requests keep running in the background. If those requests are expensive, pair Promise.all with an AbortController (covered in the next chapter).
Use Promise.allSettled when each piece stands alone
Suppose you load a dashboard with independent widgets, or send 200 notification emails. One broken widget should not blank the page, and one bad address should not hide which 199 emails went out. Promise.allSettled lets you handle each outcome on its own.
Use Promise.race when the first event of any kind decides
Promise.race is the right tool when a rejection is a valid answer, and the classic case is a timeout. The timeout promise rejects, and you want that rejection to win if it comes first. It also fits "whichever happens first" situations, such as a response arriving or a user clicking Cancel.
Use Promise.any when you want the first success
Suppose the same file is on three mirrors, or you can read a value from a cache, a replica, or the primary database. A failure from one source should not end the operation while another source might still succeed. Promise.any takes the first fulfillment. It rejects with an AggregateError only when every source has failed.
Combining Combinators
Real tasks often need two combinators layered together. A common case is a dashboard where each widget gets its own time limit and failures are reported, not thrown. You apply Promise.race to each task and then Promise.allSettled to the whole group.
const ok = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms));
async function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms);
});
try {
return await Promise.race([promise, timeout]);
} finally {
clearTimeout(timer);
}
}
async function loadDashboard() {
const widgets = {
weather: ok(80, 'Sunny, 21°C'),
news: fail(60, 'News API returned 503'),
stocks: ok(500, 'ACME +2%')
};
const names = Object.keys(widgets);
const outcomes = await Promise.allSettled(
names.map((name) => withTimeout(widgets[name], 200))
);
outcomes.forEach((outcome, i) => {
if (outcome.status === 'fulfilled') {
console.log(`${names[i]}: ${outcome.value}`);
} else {
console.log(`${names[i]}: unavailable (${outcome.reason.message})`);
}
});
}
loadDashboard();
// weather: Sunny, 21°C
// news: unavailable (News API returned 503)
// stocks: unavailable (Timed out after 200 ms)Other useful layers:
- Overall deadline on a batch:
withTimeout(Promise.all(tasks), 2000)makes the whole group fail if it is not finished in two seconds. - Fallback with a deadline:
withTimeout(Promise.any(mirrors), 1000)takes the first working mirror, but only within one second. - Successes only:
(await Promise.allSettled(tasks)).filter((r) => r.status === 'fulfilled').map((r) => r.value)keeps the successful values. Do this only when you also log or count the failures somewhere.
Common Mistakes
Using race when you meant any
This is the most frequent mix-up. If you race three mirrors and the first one to respond returns an error, Promise.race rejects even though the other two would have succeeded. If failures should be skipped, you want Promise.any.
Using all when partial results are acceptable
When a batch job uses Promise.all, one bad record makes you lose the results of every good record, and you also lose the information about which records succeeded. If the tasks are independent, Promise.allSettled is usually the honest choice.
Treating allSettled as error handling
Promise.allSettled never rejects, so your catch block never runs. Failures become plain data in the result array. If nothing reads the status field, those errors disappear without a trace.
Reading only the first error from Promise.any
When Promise.any rejects, the useful information is in err.errors, one reason per input in input order. Logging only err.message gives you a generic "All promises were rejected" and hides why each source failed.
Expecting a combinator to stop the losers
None of the four combinators cancels anything. After Promise.all fails fast, or race or any picks a winner, the other operations keep running and using network, CPU, or quota. Wire in cancellation when that matters.
Do You Need a Combinator at All?
Combinators are for tasks that are independent. If step two needs the result of step one, such as fetching a user and then fetching that user's orders, await them in sequence. A combinator gives you nothing there. If you have hundreds or thousands of independent tasks, starting them all at once with Promise.all can overwhelm a server or hit rate limits. In that case, run them with a concurrency limit, as shown in the final chapter.
Exercise
You query three regional replicas of a read-only database and want the first answer that comes back successfully. One replica is often down and fails immediately. Which combinator should you use, and what happens if you use Promise.race instead?
Show answer
Use Promise.any. It ignores rejections and fulfills with the first successful answer, rejecting with an AggregateError only if all three replicas fail. With Promise.race, the replica that is down and fails immediately usually settles first, so the race rejects even though the other replicas would have answered.
Exercise
A nightly job resizes 50 uploaded images. Each resize is independent, and the job must report which images failed. A colleague wrote await Promise.all(images.map(resize)). What is wrong, and what would you change?
Show answer
Promise.all rejects on the first failed resize, so the job loses the results and failure details of every other image, and the remaining resizes keep running unobserved. Use Promise.allSettled, then loop over the outcomes and record each one with status 'rejected' together with its image and reason. With many more images, also add a concurrency limit.
Exercise
A product page needs price and stock from two services, and it must show an error if either one fails or if both together take longer than 3 seconds. Write the expression that produces [price, stock], assuming a withTimeout(promise, ms) helper and functions getPrice() and getStock().
Show answer
const [price, stock] = await withTimeout(Promise.all([getPrice(), getStock()]), 3000); Promise.all fails fast if either service rejects, and wrapping it in withTimeout puts a single deadline on the pair.