Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel operations with Promise.all?

Tags:

I'm led to believe that Promise.all executes all the functions you pass it in parallel and doesn't care what order the returned promises finish.

But when I write this test code:

    function Promise1(){
        return new Promise(function(resolve, reject){
            for(let i = 0; i < 10; i++){
                console.log("Done Err!");
            }
            resolve(true)
        })
    }
    
    function Promise2(){
        return new Promise(function(resolve, reject){
            for(let i = 0; i < 10; i++){
                console.log("Done True!");
            }
            resolve(true)
        })
    }
    
    Promise.all([ 
        Promise1(),
        Promise2()
    ])
    .then(function(){
        console.log("All Done!")
    })

The result I get is this

Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done!

But if they're running in parallel wouldn't I expect them to be executing at the same time and give me a result like this?

Done Err!
Done True!
Done Err!
Done True!
Done Err!
Done True!
Done Err!
Done True!
Etc. Etc.?

Or am I missing something in the way I'm doing it?

like image 510
Steve Avatar asked Mar 13 '17 20:03

Steve


People also ask

What is the use of Promise all ()?

The Promise.all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.

Does Promise all run sequential?

all() method executed by taking promises as input in the single array and executing them sequentially.

Does Promise all resolve promises in order?

Here, Promise. all() method is the order of the maintained promises. The first promise in the array will get resolved to the first element of the output array, the second promise will be a second element in the output array and so on.


1 Answers

It's because your Promises are blocking and synchronous! Try something with a timeout instead of a synchronous loop:

    function randomResolve(name) {
      return new Promise(resolve => setTimeout(() => {
        console.log(name);
        resolve();
      }, 100 * Math.random()));
    }
    
    Promise.all([ 
        randomResolve(1),
        randomResolve(2),
        randomResolve(3),
        randomResolve(4),
    ])
    .then(function(){
        console.log("All Done!")
    })
like image 88
Johannes Merz Avatar answered Sep 19 '22 15:09

Johannes Merz