Sub topic 4
Promise.all: Wait for Every Promise to Fulfill
This chapter assumes you can write async functions, use await inside try/catch, and destructure arrays. It also builds on the earlier idea that work starts when you create a promise, not when you await it.
The Working Model
Promise.all takes an iterable of values, usually an array of promises, and returns one new promise. That promise:
- fulfills when every input has fulfilled, with an array of their values;
- rejects as soon as any input rejects, with that input's reason.
The result array follows the input order, not the order in which the promises finished. Any input that is not a promise is treated as an already-fulfilled promise holding that value.
A Worked Example
The program below runs as written in Node.js 18 or later.
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function loadDashboard() {
const start = Date.now();
const [user, orders, settings] = await Promise.all([
delay(300, { name: 'Ada' }),
delay(50, ['order-1', 'order-2']),
delay(100, { theme: 'dark' })
]);
console.log(user.name); // 'Ada'
console.log(orders.length); // 2
console.log(settings.theme); // 'dark'
console.log(`${Date.now() - start} ms`); // about 300 ms, not 450 ms
}
async function mixedInputs() {
const results = await Promise.all([
Promise.resolve(1),
new Promise((resolve) => setTimeout(() => resolve(2), 50)),
3
]);
console.log(results); // [1, 2, 3]
}
async function oneFails() {
try {
await Promise.all([
delay(100, 'slow'),
Promise.reject(new Error('boom'))
]);
} catch (err) {
console.log(err.message); // 'boom'
}
}
loadDashboard().then(mixedInputs).then(oneFails);The total time equals the slowest input, because all three timers run at the same time. Because the order is fixed, you can destructure the results by position and know which value is which.
Mapping Over Data
Most real uses build the input array with map:
const delay = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function fetchUser(id) {
return delay(100 * id, { id, name: `user-${id}` });
}
async function main() {
const ids = [3, 1, 2];
const users = await Promise.all(ids.map((id) => fetchUser(id)));
console.log(users.map((u) => u.id)); // [3, 1, 2]
}
main();ids.map(...) calls fetchUser for every id right away, so all the requests are in flight before Promise.all starts waiting.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Passing functions: `Promise.all([fetchA, fetchB])` | The functions are treated as plain values. Nothing runs, and you get the functions back. | Call them: `[fetchA(), fetchB()]` |
| `await` inside a `for` loop before collecting | The tasks run one by one | Create all the promises first, then await `Promise.all` |
| `ids.forEach(async ...)` | Nothing waits for the tasks, and their errors go unhandled | Use `map` and pass the result to `Promise.all` |
| Forgetting `await` or `return` on `Promise.all` | The code continues before the results exist | `await` the result or return it |
| Using it when some failures are acceptable | One rejection throws away all the other values | Use `Promise.allSettled` (covered later) |
When to Reach for It
Use Promise.all when the tasks are independent and you need all of their results to continue, so that any single failure means the whole operation has failed. Loading the data for one page is a typical case.
Exercise
What does this log, and roughly how long does it take? const r = await Promise.all([delay(200, 'x'), 'y', delay(100, 'z')]); console.log(r);
Show answer
It logs ['x', 'y', 'z'] after about 200 ms. The plain value 'y' counts as already fulfilled, results keep input order, and the total time equals the slowest input (200 ms).
Exercise
A teammate writes const results = await Promise.all([loadA, loadB]); where loadA and loadB are async functions. Why is results not the loaded data?
Show answer
The array holds the functions themselves, not promises. Promise.all treats non-promise values as already fulfilled, so it returns [loadA, loadB] without calling either one. Write Promise.all([loadA(), loadB()]) instead.