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:

JavaScript

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

JavaScript

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?

JavaScript

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.

JavaScript

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.

JavaScript
Advertisement