Running Promises in Parallel - The Complete Node.js course

Hi, I’m currently doing the course by Mosh - The Complete Node.js course. I got up to Asynchronous JavaScript part 10: Running Promises in Parallel.

How this code should work is that Promise 1 starts, then Promise 2 starts, then 1 finishes, then 2 finishes.

But seemingly, Promise 1 is starting and finishing, and then Promise 2 is starting. This would be blocking code and would defeat the purpose of the Promise.

The reason I think this is for the following reason. For example, with Promise.race. This is fulfilled when 1 of the promises is fulfilled. Mosh’s terminal looks like this:

Async operation 1…
Async operation 2…
1 (The result from Promise.race)

This terminal suggests that Async op 1 starts, then Async op 2 starts, then 1 finishes which is when promise.race returns.

However, my terminal looks like the following:

Async operation 1…
1 (The result from Promise.race)
Async operation 2…

So, promise.race is returned because Async op 1 is fulfilled. Wouldn’t this suggest that Async op 1 is starting and finishing before async operation 2 starts? Or is something else happening here?

I followed his code, so nothing is different as far as I know. Any information about this would be appreciated. Thank you.

Possibly, this is just a result of async code racing. You may get different results on different machines unless you ensure that async operation 1 is definitely going to take longer than async operation 2.

For example:

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

delay(5000).then(() => console.log("5s finished"));
delay(1000).then(() => console.log("1s finished"));

Logs:

1s finished
5s finished

Even though the 5 second delay was started first. If the first promise completes fast enough, you can have the first one completely finish before the second one even starts!

That makes sense. I appreciate your response!

I did another test where I made the first one delayed by 10000 and the 2nd one delayed by 5000. Obviously the 2nd one finished first. The first one finished about 5 to 7 seconds later which is what I was expecting and suggests it isn’t blocking code. So, this all checks out. I guess I can chalk it up to async code racing and my machine as you suggested.

1 Like