Node.js
await with Promise.all
Learn parallel operations with await Promise.all.
await Promise.all
You can await the result of Promise.all; when all parallel jobs finish, the value arrives as an array. This is much more readable than a then chain.
async function load() {
const values = await Promise.all([loadA(), loadB()]);
console.log(values);
}
Here both load calls start in parallel; await resumes when both finish. The total time is roughly that of the slowest. The order in the array matches the input array.
Parallel vs sequential
Whether two async jobs run in parallel or sequentially depends on how you use await. For parallel, pass both to Promise.all and await once. For sequential, await each separately; the total time is the sum of both.
// parallel
const [a, b] = await Promise.all([loadA(), loadB()]);
// sequential
const a = await loadA();
const b = await loadB();
Parallel is usually faster; but if one job's result feeds the other, you must use sequential. The right choice greatly affects the application's speed.
Exercise Your turn: await Promise.all
Define async function load(). Write const values = await Promise.all([Promise.resolve(1), Promise.resolve(2)]). Log the sum with console.log(values[0] + values[1]). Call load().
Show example solution
async function load() {
const values = await Promise.all([Promise.resolve(1), Promise.resolve(2)]);
console.log(values[0] + values[1]);
}
load();
Test yourself
-
When does await Promise.all([a, b]) REJECT?
- When both a and b succeed
- When a returns immediately
- When b never completes
- When either a or b rejects
Show answer
When either a or b rejects — The first rejection rejects the whole Promise.all.
-
await + Promise.all
- await
- waits for the result
- Promise.all
- combines in parallel
- order
- matches the input array
-
Fill in the blank: parallel await
async function load() {
const values = ____ Promise.all([Promise.resolve(1), Promise.resolve(2)]);
console.log(values[0] + values[1]);
}
load();
Show answer
async function load() {
const values = await Promise.all([Promise.resolve(1), Promise.resolve(2)]);
console.log(values[0] + values[1]);
}
load();
Next lesson: Sequential await