用包含异步等待的数组foreach等待 [英] await with array foreach containing async await
本文介绍了用包含异步等待的数组foreach等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在node.js中,我需要使用一个包含Array.foreach的function procesMultipleCandidates ()
1,该进程将每个元素插入db.但整个功能应在完成所有插入操作后返回响应
In node.js I need to use a function procesMultipleCandidates ()
1 which contains Array.foreach which process insert every element into db. but the entire function should return response after completing all insertion operation
JavaScript代码
async function procesMultipleCandidates (data) {
let generatedResponse = []
await data.forEach(async (elem) => {
try {
// here candidate data is inserted into
let insertResponse = await insertionInCandidate(elem)
//and response need to be added into final response array
generatedResponse.push(insertResponse)
} catch (error) {
console.log('error'+ error);
}
})
console.log('complete all') // gets loged first
return generatedResponse // return without waiting for process of
}
并且如上所述,最后一个return语句不等待foreach
执行首先完成.
And as described above last return statement not waiting for the foreach
execution to complete first.
推荐答案
使用 Array.prototype.map 和 Promise.all :
async function procesMultipleCandidates (data) {
let generatedResponse = []
await Promise.all(data.map(async (elem) => {
try {
// here candidate data is inserted into
let insertResponse = await insertionInCandidate(elem)
// and response need to be added into final response array
generatedResponse.push(insertResponse)
} catch (error) {
console.log('error'+ error);
}
}))
console.log('complete all') // gets loged first
return generatedResponse // return without waiting for process of
}
或使用 for/of
循环,如果您不希望循环并行运行:
Or use a for/of
loop if you don't want the loop run in parallel:
async function procesMultipleCandidates (data) {
let generatedResponse = []
for(let elem of data) {
try {
// here candidate data is inserted into
let insertResponse = await insertionInCandidate(elem)
// and response need to be added into final response array
generatedResponse.push(insertResponse)
} catch (error) {
console.log('error'+ error);
}
}
console.log('complete all') // gets loged first
return generatedResponse // return without waiting for process of
}
这篇关于用包含异步等待的数组foreach等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文