javascriptasync-awaitpromise

Why do these two await lines execute in parallel?


In below code, both c and c2 variables are awaiting for different promise instances and should run in serial but when run, the program completes in 100 miliseconds instead of 200.

function a1() {
  return new Promise((x, y) => {
    setTimeout(function () {
      x(5);
    }, 100);
  });
}

async function run() {
  let t1 = Date.now();
  let b = a1();
  let b2 = a1();

  let c = await b;
  let c2 = await b2;
  console.log(Date.now() - t1);
}

run().then(function () {
  console.log('@');
});

Why is this behavior legal if await is defined as a serial operation?


Solution

  • You are calling a1() for both b and b2 when declaring them. Thus, by the time you await, the timeouts have already run and they each hold a promise, the await just resolves those promises.

    If you want to see the full delay you should asign a1 to your b variables and then await the calls when declaring c, or simply await a1() twice.

      let b = a1;
      let b2 = a1;
    
      let c = await b();
      let c2 = await b2();
    

    function a1() {
      return new Promise((x, y) => {
        setTimeout(function () {
          x(5);
        }, 100);
      });
    }
    
    async function run() {
      let t1 = Date.now();
    
      let b = await a1();
      let b2 = await a1();
      
      console.log(Date.now() - t1);
    }
    
    run().then(function () {
      console.log('@');
    });