CodeBlanks Logo Icon CodeBlanks

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.

Practice 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().

Starter code

index.js
// Define async function load
// Get two values with await Promise.all, log the sum with console.log
// Finally call load

Sample solution

index.js
async function load() {
  const values = await Promise.all([Promise.resolve(1), Promise.resolve(2)]);
  console.log(values[0] + values[1]);
}
load();

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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 Correct answer

Explanation: The first rejection rejects the whole Promise.all.

2 await + Promise.all

Term Meaning
await waits for the result
Promise.all combines in parallel
order matches the input array

3 Fill in the blank: parallel await

Question
async function load() {
  const values = ____ Promise.all([Promise.resolve(1), Promise.resolve(2)]);
  console.log(values[0] + values[1]);
}
load();
Answer
async function load() {
  const values = await Promise.all([Promise.resolve(1), Promise.resolve(2)]);
  console.log(values[0] + values[1]);
}
load();

Explanation: await waits for the Promise.all result.

All lessons in Beginner