[英]How to resolve promise making function in map chain?
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.我希望下面代码中的所有 slowAdd() 并行发生,但在它们全部解决之前我不想执行 next.map() 步骤。 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:将其放入
Promise.all
中,然后您将需要另一个.map
在.then
中以进行后续操作:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.