JavaScriptMedium
What is Promise.all()?
Promise.all(iterable) runs promises concurrently and returns a single promise that fulfills with an array of all results (in the original order) once every one succeeds, or rejects immediately with the first error.
Behaviour
- Order is preserved: results match the input order, not the order they finished.
- Fail-fast: as soon as one promise rejects, the combined promise rejects with that reason. The other operations keep running in the background (promises cannot be cancelled), but their results are ignored.
- Non-promise values in the array are treated as already fulfilled.
- An empty array fulfills immediately with
[].
When to use it
When you need all results and the operations are independent: loading a page's user, settings and notifications at once; uploading several files; fetching several pages of data.
Related combinators
Promise.allSettled: wait for all and get each outcome, success or failure. Use when partial success is fine.Promise.race: settles with the first promise to settle (success or failure). Good for timeouts.Promise.any: fulfills with the first success; rejects with anAggregateErroronly if all fail.
Watch out for
- Too much concurrency:
Promise.all(10_000 requests)fires everything at once. Batch the work or use a concurrency limit. - Cancellation: pair it with an
AbortControllerif you want the other requests to stop when one fails.
Code example
js
1const task = (name, ms, fail = false) =>2 new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(`${name} failed`)) : resolve(name)), ms));34// All succeed: results come back in input order, not finish order5const t = Date.now();6const results = await Promise.all([task("user", 60), task("settings", 20), task("notifications", 40)]);7console.log(results); // ["user", "settings", "notifications"]8console.log(`took about the slowest one, not the sum: ${Date.now() - t < 100}`); // true910// Fail-fast: rejects with the first error11try {12 await Promise.all([task("a", 50), task("b", 10, true), task("c", 30)]);13} catch (e) {14 console.log(e.message); // b failed15}1617// Non-promise values are allowed18console.log(await Promise.all([1, Promise.resolve(2), task("three", 5)])); // [1, 2, "three"]1920// Limit concurrency by processing in batches21async function inBatches(items, size, worker) {22 const out = [];23 for (let i = 0; i < items.length; i += size) {24 out.push(...(await Promise.all(items.slice(i, i + size).map(worker))));25 }26 return out;27}28console.log(await inBatches([1, 2, 3, 4, 5], 2, async (n) => n * n)); // [1, 4, 9, 16, 25]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.