Blake Blake - 14 days ago 5
Javascript Question

When does JavaScript `await` actually wait?

I was reading this article, and wondering why in the first snippet the seconde

wait()
waits the first
wait()
to finish whereas in the seconde snippet two
wait()
run async?

async function series() {
await wait(500);
await wait(500);
return "done!";
}

async function parallel() {
const wait1 = wait(500);
const wait2 = wait(500);
await wait1;
await wait2;
return "done!";
}

function wait(ms) {
return new Promise(r => setTimeout(r, ms));
}

Answer

In your first function:

async function series() {
    await wait(500); // 1
    await wait(500); // 2
    return "done!";
}

You're telling JS to await the first wait as soon as it's started.
This means the second wait(500) can't start, before the first one finishes:

  1. Trigger wait(500) // 1
  2. wait for that to pass
  3. Trigger wait(500) // 2
  4. wait for that to pass

In the second function:

async function parallel() {
    const wait1 = wait(500); // 1
    const wait2 = wait(500); // 2
    await wait1;
    await wait2;
    return "done!";
}

Both wait calls are started, before the code is told to await the results.

  1. Trigger wait(500) // 1
  2. Trigger wait(500) // 2
  3. Wait for wait1 to pass,
  4. wait for wait2 to pass

Because wait1 and wait2 are triggered immediately after each other, they're practically running in parallel.

Imagine this:

If 2 people both start a stopwatch at the same time, if you need to wait before each stopwatch reaches 10 seconds, you still only have to wait 10 seconds.
In the series function, on the other hand, the second stopwatch can't start before the first one finishes.

Comments