3

I have 2 code snippets (Parallel,Sequential) execution of a simple Async function on an array with reduce. I do not understand, why the execution does not start until I call Promise.all. Is this the best way to do this?

// Function returning promise with root value
async function proot(x) {
    return new Promise((res,rej)=>{ 
        setTimeout( () => { 
            console.log(x*x);
            res(x*x) 
        },1000)    
    })
}

// Parallel Execution
var arr1 = [2,3,4].reduce((prev,next)=>{
    return prev.concat(proot(next))
},[])
arr1 = await Promise.all(arr1)

// Sequential Execution
var arr2 = [2,3,4].reduce( async (prev,next)=>{
    return (await prev).concat(await proot(next))
},Promise.resolve([]))
arr2 = await Promise.all([arr2])
1
  • Just wanted to add that the second sequential execution will work without calling Promise.all() when I do NOT use debugging. Perhaps this has something to do with my IDE and mocha rather than javascript. Commented Apr 14, 2017 at 15:59

1 Answer 1

3

The code inside the promise gets executed when you call the function that returns the promise:

// Parallel Execution
var arr1 = [2,3,4].reduce((prev,next)=>{
    return prev.concat(proot(next))
},[])

But it returns a promise instead of a value. You will need to handle the promise to get the value it resolves.

You don't need to use reduce. Map will work in your case:

var arr = [2,3,4].map((n) => proot(n));
Promise.all(arr).then((values) => {})

Or:

var arr = [2,3,4].map(async (n) => await proot(n));
Sign up to request clarification or add additional context in comments.

1 Comment

Alberto, I will mark your answer correct, as this solves my posted question. I actually have to use the concat inside the reduce as I may need to insert multiple array element in place of a single member of my array. In the meantime I have just realized that while I am debugging the setTimeout function somehow do net get triggered and that's why I did not get the results on my screen until I called Promise.all. so I actually do not need to call the promise.all to get the results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.