【发布时间】:2021-08-24 19:42:11
【问题描述】:
我在javascript节点中有这个功能
exports.getUserEmailByAccess = async (moduleType) => {
let emailList = []
const foundUsers = await Access.find({moduleType:moduleType})
console.log(foundUsers);
await foundUsers.forEach(access => {
User.findById(access.userId)
.then(foundUser => {
console.log(foundUser.workerEmail);
emailList.push(foundUser.workerEmail)
})
});
console.log(emailList);
return emailList
}
我想要的是通过循环对象数组推入 emailList 数组,上述方法导致一个空数组,所以我尝试了以下不同的方式
exports.getUserEmailByAccess = async (moduleType) => {
let emailList = []
const foundUsers = await Access.find({moduleType:moduleType})
console.log(foundUsers);
await foundUsers.forEach(access => {
const foundUser = User.findById(access.userId)
console.log(foundUser.workerEmail);
emailList.push(foundUser.workerEmail)
});
console.log(emailList);
return emailList
}
通过这样做,数组列表被填满,但有一个 [undefined]strong text 值,我来自一个不起眼的 python 控制结构背景,请我知道为什么我不能即使在使用 async/await 之后也将数据推送到数组中
【问题讨论】:
-
确实
foundUsers.forEach返回一个 Promise - 如果没有,你不能等待它......我假设那不是数组forEach,在这种情况下,永远不要将 Array forEach 与 async/await 一起使用,除非你真的知道自己在做什么——即使那样,总有更好的方法来做到这一点 -
@Bravo 是对的,
forEach不会等待承诺被解决,而是应该使用for循环。 -
答案取决于您是否可以并行或串行
User.findById
标签: javascript node.js asynchronous async-await