Node.js
Promise.all
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.
Exercise 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])).
Show example solution
const p1 = Promise.resolve(10);
const p2 = Promise.resolve(20);
Promise.all([p1, p2]).then(values => console.log(values[0] + values[1]));
Test yourself
-
When does Promise.all reject?
- When the first Promise resolves
- When any Promise in the array rejects
- When all Promises reject
- When all Promises fulfill
Show answer
When any Promise in the array rejects — The first rejected Promise rejects the whole chain.
-
Fill in the blank: Promise.all
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
____([p1, p2]).then(values => console.log(values));
Show answer
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
Promise.all([p1, p2]).then(values => console.log(values));
-
Promise.all behaviours
- Promise.all
- resolves when all done
- parallel
- runs concurrently
- one rejects
- rejects the whole
Next lesson: Promise.race