javascript - Async/Await inside Array function reduce -


i have 2 code snippets (parallel,sequential) execution of simple async function on array reduce. not understand, why execution not start until call promise.all. best way this?

// function returning promise 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]) 

the code inside promise gets executed when call function returns promise:

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

but returns promise instead of value. need handle promise value resolves.

you don't need use reduce. map work in 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)); 

Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -