CodeBlanks Logo Icon CodeBlanks

Sequential await

Learn sequential operations with await.

What is sequential await?

When you write several await calls in a row, each one starts only after the previous one finishes. This is called sequential await; the total time is the sum of each step's time.

async function run() {
  const a = await loadA();
  const b = await loadB();
  console.log(a, b);
}

Here loadB starts only after loadA finishes. If loadB depends on loadA's result, this order is required; but if they are independent, you can save time by running them in parallel.

Practice Your turn: sequential await

Define async function run(). Write const a = await Promise.resolve(5). Write const b = await Promise.resolve(10). Log the sum with console.log(a + b). Call run().

Starter code

index.js
// Define async function run
// Make two await Promise.resolve calls, log the sum with console.log
// Finally call run

Sample solution

index.js
async function run() {
  const a = await Promise.resolve(5);
  const b = await Promise.resolve(10);
  console.log(a + b);
}
run();

Expected output

15

When to use sequential?

Sequential await is required when one job's result feeds the next. For example, if you first fetch a user id and then use that id to fetch the profile, the second call needs the first's result; you cannot run them in parallel.

const user = await getUser();
const profile = await getProfile(user.id);

But for independent jobs, parallel execution shortens the total time. The question to ask: Does the second job need the first's result? If yes, sequential; if not, parallel.

Questions and answers

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

1 What happens if you use sequential await for two independent async jobs?

  • They run in parallel and finish faster
  • They run sequentially and take longer in total Correct answer
  • Both are skipped
  • Promise.race starts

Explanation: Sequential await wastes time on independent jobs.

2 Fill in the blank: sequential await

Question
async function run() {
  const a = await Promise.resolve(1);
  const b = ____ Promise.resolve(2);
  console.log(a + b);
}
Answer
async function run() {
  const a = await Promise.resolve(1);
  const b = await Promise.resolve(2);
  console.log(a + b);
}

Explanation: The second await runs after the first.

3 Sequential vs parallel

Term Meaning
sequential longer total time
parallel shorter total time
dependent needs sequential

All lessons in Beginner