Promise.all
- Node.js course
- Beginner
- Lesson 90/116
- 5 min
Learn parallel promises with Promise.all.
What is Promise.all?
To start several async jobs in parallel and wait for all of them you use Promise.all. It takes an array of Promises and, when all are fulfilled, returns an array of their results. Since the jobs run in parallel, the total time is roughly that of the slowest one.
Promise.all([p1, p2, p3])
.then(values => console.log(values));Important: if any Promise in the array rejects, Promise.all immediately rejects with that error; even if the others finish, no result array is produced. When all Promises succeed you get the array; if even one rejects, you get an error.
Result order
The array returned by Promise.all keeps the order of the input Promises. Even if the second Promise finishes before the first, it still appears in the second position of the result array. This is handy when you need to process parallel results in a fixed order.
Promise.all([p1, p2])
.then(values => console.log(values[0], values[1]));Here p1 and p2 run in parallel; once both finish, the result array arrives as [result1, result2]. Speed differences do not matter; the order matches the input.
Practice Your turn: parallel with Promise.all
Create two Promises: const p1 = Promise.resolve(10) and const p2 = Promise.resolve(20). Call Promise.all([p1, p2]) and log the sum with .then(values => console.log(values[0] + values[1])).
Starter code
// Create p1 and p2 Promises
// Combine with Promise.all, log the sum in .thenSample solution
const p1 = Promise.resolve(10);
const p2 = Promise.resolve(20);
Promise.all([p1, p2]).then(values => console.log(values[0] + values[1]));Expected output
30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does Promise.all reject?
- When the first Promise resolves
- When any Promise in the array rejects Correct answer
- When all Promises reject
- When all Promises fulfill
Explanation: The first rejected Promise rejects the whole chain.
2 Fill in the blank: Promise.all
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
____([p1, p2]).then(values => console.log(values));
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
Promise.all([p1, p2]).then(values => console.log(values));
Explanation: Promise.all returns all results as an array.
3 Promise.all behaviours
| Term | Meaning |
|---|---|
Promise.all |
resolves when all done |
parallel |
runs concurrently |
one rejects |
rejects the whole |