ucipass
ucipass

Reputation: 1068

Async/Await inside Array function reduce

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])

Upvotes: 3

Views: 2604

Answers (1)

Alberto Centelles
Alberto Centelles

Reputation: 1253

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));

Upvotes: 3

Related Questions