I've seen a few people around the internet praise Promise.all for allowing your promises to run in parallel. While the spirit of this tip is correct, in that Promise.all may speed up the execution of multiple promises, the word "parallel" is technically incorrect.

In this article, I will explain, as simply as I can, how Promise.all works and why it can not run in parallel.

Sequential vs. Concurrent vs. Parallel

To understand how JavaScript's Promise.all works, we first need to understand three different execution paradigms, sequential, concurrent, and parallel.

To illustrate these paradigms, I will use the following two promises.

None

Sequential execution means that one promise is executed and resolved, then the next promise is executed and resolved until the program finishes. The following code executes sequentiality.

Sleep function one executes and is resolves, then sleep function two executes and resolves, finally the program exits.

Concurrent execution on the other hand means one promise will execute and without waiting for it to resolve, the next promise will execute, finally, the program will exit when all promises are resolved. The following code executes concurrently.

Sleep function one will execute and without waiting for it to resolve, sleep function two will execute. When both promises have been resolved, the program exits.

As you can see, Promise.all executes code concurrently, but what is parallel execution?

JavaScript is single-threaded and can only perform a single chunk of work at a time, so parallel execution is not possible with JavaScript, except for some circumstances such as web workers.

Parallel execution means that more than one unit of code can execute simultaneously. In the example above, it would mean that sleep function one and sleep function two execute at the exact same time, which is not what happens.

So, why use Promise.all?

Promise.all is extremely powerful, especially when you're performing I/O operations, where your application doesn't have to do any work after the promise execution, such as network or database requests. Allowing more than one request to be sent out at a time means your application's execution won't be blocked while it waits for the network request to respond.

🌎 Follow me here:

YouTube: https://www.youtube.com/TomDoesTech

Discord: https://discord.gg/4ae2Esm6P7 Twitter: https://twitter.com/tomdoes_tech Facebook: https://www.facebook.com/tomdoestech​ Instagram: https://www.instagram.com/tomdoestech​ ☕ Buy me a coffee: https://www.buymeacoffee.com/tomn

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.