如何解决地图链中的承诺功能?
How to resolve promise making function in map chain?
我希望下面代码中的所有 slowAdd() 并行发生,但我不想在它们全部解决之前执行下一个 .map() 步骤。怎么做?
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());
将其放入 Promise.all
,然后您需要在 .then
中放置另一个 .map
以进行后续操作:
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()
我希望下面代码中的所有 slowAdd() 并行发生,但我不想在它们全部解决之前执行下一个 .map() 步骤。怎么做?
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());
将其放入 Promise.all
,然后您需要在 .then
中放置另一个 .map
以进行后续操作:
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()