Sub topic 4
Promise.all: Wait for Every Promise to Fulfill
This chapter assumes you can write async functions, use await and try/catch, and create promises with new Promise. It also builds on the earlier idea that a combinator takes an iterable and returns one promise. The examples use top-level await, so run them as ES modules (save them as .mjs files in Node.js 14.8 or later) or paste them into a browser console.
Promise.all is the combinator you will reach for most often. You give it a group of independent tasks that you have already started. It waits until every task succeeds, then gives you all the results together.
The Contract
Promise.all(iterable) returns a single promise that settles by one of two rules:
| Situation | What the returned promise does |
|---|---|
| Every input fulfills | Fulfills with an array of the values, in input order |
| Any input rejects | Rejects with the reason of the first input to reject |
| Inputs are still pending and none has rejected | Stays pending |
The order rule matters most in practice. The result array matches the order of the inputs, not the order in which the inputs finished. Item 0 of the result belongs to item 0 of the input, even if item 0 was the slowest to finish.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const results = await Promise.all([
delay(300, 'slow'),
delay(10, 'fast'),
'plain value'
]);
console.log(results); // ['slow', 'fast', 'plain value']The third input is a string, not a promise. Promise.all passes each input through Promise.resolve, so a plain value counts as already fulfilled. A thenable (any object with a then method) is adopted the same way.
How It Works Internally
Writing a simplified version yourself shows why the order rule and the plain-value rule hold. The specification follows the same plan: it keeps a counter of unfinished inputs, and each input fills its own slot by index.
function promiseAll(iterable) {
return new Promise((resolve, reject) => {
const results = [];
let remaining = 1; // starts at 1 so we cannot resolve mid-iteration
let index = 0;
try {
for (const item of iterable) {
const i = index++;
results[i] = undefined;
remaining++;
Promise.resolve(item).then((value) => {
results[i] = value;
remaining--;
if (remaining === 0) resolve(results);
}, reject);
}
} catch (err) {
reject(err); // iterating the input threw
return;
}
remaining--; // release the initial 1
if (remaining === 0) resolve(results);
});
}
console.log(await promiseAll([Promise.resolve(1), 2, Promise.resolve(3)])); // [1, 2, 3]
console.log(await promiseAll(new Set(['x', 'y']))); // ['x', 'y']The code shows these points:
- Input order is kept because each callback captures its own index
iand writes toresults[i]. Finishing order never decides where a value goes. - Plain values work because
Promise.resolve(item)wraps them. - Any iterable works. Arrays,
Sets, generators, andMapentries are all accepted, because the function usesfor...of. The result is always a plain array. - The counter starts at 1. Without that extra count, a resolved input could not bring the counter to zero before the loop finished, because callbacks run as microtasks. The extra 1 still guards against an early resolve during iteration, and it handles the empty case: with no inputs, the final decrement reaches zero and the promise fulfills with
[]. - Rejection is passed straight to
reject. The first rejection settles the outer promise. Later calls toresolveorrejectdo nothing, because a promise settles only once. The next chapter covers what happens to the inputs that are still running.
A Realistic Example
The usual case is a set of requests that do not depend on each other. You start them all at once and use their results together.
const fakeApi = {
user: (id) => delay(120, { id, name: 'Ada' }),
orders: (id) => delay(200, [{ orderId: 1, userId: id }]),
settings: (id) => delay(80, { userId: id, theme: 'dark' })
};
async function loadDashboard(userId) {
const [user, orders, settings] = await Promise.all([
fakeApi.user(userId),
fakeApi.orders(userId),
fakeApi.settings(userId)
]);
return { user, orders, settings };
}
console.time('dashboard');
console.log(await loadDashboard(7));
console.timeEnd('dashboard'); // about 200 ms, not 400 msArray destructuring works well here because the result order is guaranteed. Each name lines up with the call in the same position.
For a list of items of unknown length, use map to turn it into an array of promises:
const ids = [1, 2, 3, 4];
const users = await Promise.all(ids.map((id) => fakeApi.user(id)));
console.log(users.map((u) => u.id)); // [1, 2, 3, 4]Common Errors
Passing functions instead of promises
Promise.all needs promises, or values it can wrap. If you pass functions, it treats each function as a plain value. Nothing runs, and you get the functions back.
const wrong = await Promise.all([
() => fakeApi.user(1),
() => fakeApi.user(2)
]);
console.log(typeof wrong[0]); // 'function', the requests never ran
const right = await Promise.all([fakeApi.user(1), fakeApi.user(2)]);
console.log(right[0].name); // 'Ada'If you keep a list of task functions, call them: Promise.all(tasks.map((task) => task())).
Awaiting inside the map callback and expecting a sequence
An async callback in map returns a promise right away, so map starts every task at the same moment. That is usually what you want with Promise.all. If you meant the tasks to run one after another, or if the API limits how many requests you can make at once, map will not give you that. Use a for...of loop with await, or use the limited-concurrency pattern from the last chapter.
// All four start at once; await inside the callback does not serialize them
const loaded = await Promise.all(
ids.map(async (id) => {
const user = await fakeApi.user(id);
return user.name.toUpperCase();
})
);
console.log(loaded); // ['ADA', 'ADA', 'ADA', 'ADA']Forgetting forEach does not wait
ids.forEach(async (id) => ...) throws away the promises the callback returns, so you have nothing to pass to Promise.all. Use map.
Starting work too early or too late
Promises start running when you create them, not when you hand them to Promise.all. If you create a promise and then await something else before calling Promise.all, a rejection from the waiting promise can be reported as unhandled. Create the promises right where you combine them.
Mutating the input array afterwards
Promise.all reads the iterable once, when you call it. Pushing more promises into the same array later has no effect on the returned promise.
When Promise.all Fits
Use Promise.all when all of these are true:
- The tasks do not depend on each other's results.
- You need every result, so one failure means the whole operation has failed.
- The number of tasks is small enough to run all at once.
If partial success is acceptable, Promise.allSettled is a better fit. If you only need the first answer, Promise.race or Promise.any fits better. Later chapters cover both.
Exercise
What does this code log, and roughly how long does it take? const r = await Promise.all([delay(150, 'a'), 'b', delay(50, 'c')]); console.log(r);
Show answer
It logs ['a', 'b', 'c'] after about 150 ms. The results follow input order, not finishing order. The plain string 'b' is treated as already fulfilled. The total time equals the time of the slowest input, 150 ms, because all three were already running.
Exercise
A teammate writes const pages = await Promise.all(urls.map((url) => () => fetch(url))); and finds that no network requests happen. Explain why and fix it.
Show answer
The map callback returns a function for each URL instead of calling fetch. Promise.all treats each function as a plain value, so it fulfills right away with an array of functions, and fetch is never called. The fix is to return the promise itself: await Promise.all(urls.map((url) => fetch(url))).
Exercise
In the simplified promiseAll implementation, why does remaining start at 1 instead of 0, and what would go wrong with an empty input if it started at 0 and the final decrement were removed?
Show answer
The extra 1 guarantees the promise cannot resolve before the loop has counted every input. It is released by the decrement after the loop. If the counter started at 0 and the final check were removed, an empty iterable would never reach the resolve call, because no input callback would run. The returned promise would stay pending forever instead of fulfilling with [].