Skip to content
Advertisement

Why do async await and Promise.all have the same running time?

I have created three Promises as follows and awaited them, expecting them to take 6000 milliseconds:

let PromiseOne = new Promise(resolve => {
  setTimeout(() => {
    resolve('Promise One');
  }, 2000);
});

let PromiseTwo = new Promise(resolve => {
  setTimeout(() => {
    resolve('Promise Two');
  }, 2000);
});

let PromiseThree = new Promise(resolve => {
  setTimeout(() => {
    resolve('Promise Three');
  }, 2000);
});

(async() => {
  console.time();
  let ResponseOne = await PromiseOne;
  let ResponseTwo = await PromiseTwo;
  let ResponseThree = await PromiseThree;

  console.log(ResponseOne, ResponseTwo, ResponseThree);
  console.timeEnd();
})();

But, I have received an unexpected console message as follows.

Promise One Promise Two Promise Three
default: 2.004s

As I know, each await has 2000ms of running time. But, It doesn’t.

In this case, what is the difference between my code above using async/await and the code below using Promise.all?

let PromiseOne = new Promise(resolve => {
  setTimeout(() => {
    resolve('Promise One');
  }, 2000);
});

let PromiseTwo = new Promise(resolve => {
  setTimeout(() => {
    resolve('Promise Two');
  }, 2000);
});

let PromiseThree = new Promise(resolve => {
  setTimeout(() => {
    resolve('Promise Three');
  }, 2000);
});

(() => {
  Promise.all([PromiseOne, PromiseTwo, PromiseThree]).then(res => {
    console.log(res);
  });
})();

Advertisement

Answer

In both cases, you’re constructing all the Promises immediately. After the declaration of PromiseThree ends, for both, you’re left with 3 promises, each of which resolves after 2 seconds. No matter what happens later in the script, each of those will resolve after 2 seconds.

If you use Promise.all, all of the promises will have resolved after 2 seconds.

If you use async/await, the first one you wait for will take 2 seconds to resolve. At that same time, the other two will have resolved, so doing await PromiseTwo and await PromiseThree will take next to no time at all – so, still a total of 2 seconds.

// at this point, each promise has been created and each will take 2 seconds
(async() => {
  console.time();
  // 2 seconds for the below line
  let ResponseOne = await PromiseOne;
  // after 2 seconds, all have resolved; below line takes no time at all
  let ResponseTwo = await PromiseTwo;
  // same as above
  let ResponseThree = await PromiseOne;

It’d be different if you constructed the other promises after awaiting the previous ones – in which case they’d run in serial as you’re expecting with await.

let makePromise = () => new Promise(resolve => {
  setTimeout(() => {
    resolve();
  }, 2000);
});
console.log('starting');
(async () => {
  console.time();
  await makePromise();
  await makePromise();
  await makePromise();
  console.timeEnd();
})();
Advertisement