Sub topic 3
When Every Input Rejects: AggregateError
This chapter assumes you know async/await, try/catch, and the four combinators covered earlier. Run the snippets as ES modules (for example, node file.mjs) so that top-level await works.
When Every Input Rejects: AggregateError
Promise.any ignores rejections until one input fulfills. If every input rejects, it rejects with an AggregateError. That error's errors array lists every reason in input order.
try {
await Promise.any([
Promise.reject(new Error('A')),
Promise.reject(new Error('B'))
]);
} catch (err) {
console.log(err instanceof AggregateError); // true
console.log(err.errors.map((e) => e.message)); // ['A', 'B']
}A common mistake is to read err.message and treat it as the cause. The real causes are in err.errors.
Edge Cases: Empty Iterables and Plain Values
Every combinator treats a plain value such as 3 as an already-fulfilled promise. Empty input is less consistent across the four:
console.log(await Promise.all([])); // []
console.log(await Promise.allSettled([])); // []
try {
await Promise.any([]);
} catch (err) {
console.log(err instanceof AggregateError); // true
}
// Promise.race([]) never settles; awaiting it would wait forever.Choosing the Right Combinator
| Need | Combinator | Settles when |
|---|---|---|
| All results, and any failure aborts the whole job | `Promise.all` | All fulfill, or the first one rejects |
| Every outcome, so you can report partial failure | `Promise.allSettled` | All settle |
| Whatever finishes first, such as a timeout | `Promise.race` | The first one settles |
| The first success, with fallbacks | `Promise.any` | The first one fulfills, or all reject |
Combinators Don't Cancel: Using AbortController
When a combinator settles, the other operations keep running. To stop them, pass one shared AbortController signal to every operation and call abort() once you have the result:
async function fetchFastest(urls) {
const controller = new AbortController();
try {
return await Promise.any(
urls.map((url) =>
fetch(url, { signal: controller.signal }).then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status} from ${url}`);
return res;
})
)
);
} finally {
controller.abort();
}
}Running Large Batches with a Concurrency Limit
If you pass 10,000 requests to Promise.all, all of them start at once. A fixed pool of workers keeps at most limit tasks in flight, and results still come back in input order:
async function mapWithLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const i = next++;
results[i] = await fn(items[i], i);
}
}
const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker());
await Promise.all(workers);
return results;
}Await tasks one at a time when each depends on the one before. Use unbounded concurrency for a small set of independent tasks. Use a limit for large batches.
Exercise
You call Promise.any on three mirror URLs and all three fail. Where do you find why each one failed, and in what order are the reasons listed?
Show answer
The promise rejects with an AggregateError. Each failure reason is in its errors array, listed in input order, not in the order the failures happened.
Exercise
What does await Promise.race(tasks) do when tasks is an empty array?
Show answer
It never settles, so the await waits forever. Check tasks.length before calling it.