natevw
natevw

Reputation: 17902

When is `await` resolved simultaneously?

The MDN documentation for async function currently gives the following combined example of two ways to use await. I've reordered it just a bit for emphasis:

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}


async function add1(x) {
  const a = await resolveAfter2Seconds(20);
  const b = await resolveAfter2Seconds(30);
  return x + a + b;
}

async function add2(x) {
  const p_a = resolveAfter2Seconds(20);
  const p_b = resolveAfter2Seconds(30);
  return x + await p_a + await p_b;
}


add1(10).then(v => {
  console.log(v);  // prints 60 after 4 seconds.
});

add2(10).then(v => {
  console.log(v);  // prints 60 after 2 seconds.
});

This was a bit surprising to me. Why does

const a = await resolveAfter2Seconds(20);
const b = await resolveAfter2Seconds(30);
return x + a + b;

resolve the two promises sequentially, while

return x + await p_a + await p_b;

seemingly resolves the two promises simultaneously? Is this behavior specified for await specifically, or a natural consequence of something else?

Upvotes: 5

Views: 133

Answers (1)

Cody Geisler
Cody Geisler

Reputation: 8617

async function add2(x) {
  const p_a = resolveAfter2Seconds(20);
  const p_b = resolveAfter2Seconds(30);
  return x + await p_a + await p_b;
}

In this statement p_a and p_b are started in parallel (i.e., as soon as you generate the promise), so when you await p_a and p_b they would appear parallel, not sequential.

To get the other functionality (await in series) you would need to:

return x + await resolveAfter2Seconds(20) + await resolveAfter2Seconds(30);

Upvotes: 7

Related Questions