Reputation: 1331
I'd like all the slowAdd()s in the code below to happen in parallel, but I don't want to do the next .map() step until they are all resolved. How to do it?
async function slowAdd(a) {
return new Promise( (resolve,reject) => setTimeout(() => resolve(a+5), 1000) )
}
async function calcArray(list) {
return list
.map( a => a+1 )
.map( a => slowAdd(a) )
.map( a => a+1 )
}
async function main() {
const list = [1, 2, 3, 4, 5]
const newList = await calcArray(list)
console.log(newList)
}
main()
.catch(err => {
console.error(err);
})
.then(() => process.exit());
Upvotes: 0
Views: 137
Reputation: 370729
Put it in a Promise.all
, and then you'll need another .map
inside a .then
for the subsequent action:
async function slowAdd(a) {
return new Promise( (resolve,reject) => setTimeout(() => resolve(a+5), 1000) )
}
async function calcArray(list) {
return Promise.all(
list
.map( a => a+1 )
.map( a => slowAdd(a) )
)
.then(addedResults => addedResults.map( a => a+1 ));
}
async function main() {
const list = [1, 2, 3, 4, 5]
const newList = await calcArray(list)
console.log(newList)
}
main()
Upvotes: 2