CodeBlanks Logo Icon CodeBlanks

Parallel await

JavaScript course · Intermediate · Lesson 81/134

Learn to run multiple operations in parallel with Promise.all and await.

Parallel await with Promise.all

If you await several promises one by one, the total time is the sum of each. If you start them all at once and wait with Promise.all, the total time is roughly the slowest one.

async function loadDashboard() {
  const [user, posts] = await Promise.all([
    fetchUser(),
    fetchPosts()
  ]);
}

Both requests start in parallel; Promise.all waits until both settle. The results are picked in array order with destructuring.

const [user, posts] = ... assigns the first two items of the array to two variables in order (array destructuring); you will cover it in detail at the advanced level.

Why sequential await is slow

When two await calls are written one after another, JavaScript does not start the second promise until the first settles. This wastes time for independent operations. If two requests do not depend on each other, run them in parallel with Promise.all.

// Sequential: total time p1 + p2
const a = await p1();
const b = await p2();
// Parallel: total time max(p1, p2)
const [a, b] = await Promise.all([p1(), p2()]);

The result is the same; only the speed differs.

Exercise Load data in parallel

Write async function loadDashboard(). Inside it, call await Promise.all([fetchUser(), fetchPosts()]) and destructure the result as [user, posts].

Show example solution
async function loadDashboard() {
  const [user, posts] = await Promise.all([
    fetchUser(),
    fetchPosts()
  ]);
}

Test yourself

  1. Which one runs two requests in parallel?

    // A: sequential
    const a = await p1(); const b = await p2();
    // B: parallel
    const [a, b] = await Promise.all([p1(), p2()]);
    • Only A (sequential await)
    • Only B (Promise.all)
    • Both run in parallel
    • Both run sequentially
    Show answer

    Only B (Promise.all) — Correct! Promise.all starts both promises at once; sequential await is not parallel.

  2. Add Promise.all

    async function loadDashboard() {
      const [user, posts] = await ____([fetchUser(), fetchPosts()]);
    }
    Show answer
    async function loadDashboard() {
      const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);
    }
  3. Match parallel and sequential await

    await Promise.all([p1(), p2()])
    runs in parallel
    await p1(); await p2();
    runs sequentially
    Promise.race([p1(), p2()])
    returns first to settle
    const [a, b] = await ...
    picks results in array order

All lessons in Intermediate