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());
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.