javascript - 异步添加后的空字段
问题描述
我正在尝试从文档中获取电子邮件、名字并用我的结果更改另一个字段中的字段,当我在等待之后执行 console.log(currentSenders) 时,我得到了我需要的所有数据,当我尝试推送我的结果是对象,它推送一个空数组。
await cars.forEach(async (car) => {
await car.senders.slice(1).forEach(async (senderId) => {
currentSender = await Meteor.users.findOne({ _id: senderId })
currentSenders.push({
email: currentSender.emails[0].address,
firstname: currentSender.profile.name
})
console.log(currentSenders) // i get all the data i need
})
box.senders = currentSenders //i want to insert the array currentSender into senders
console.log(box) //the field box.senders is an empty array instead of being populated
})
解决方案
forEach 不能以您期望的方式等待,您必须在一个很好的旧 for 循环中执行它,请参阅此答案: Using async/await with a forEach loop
推荐阅读
- javascript - 组之间的正则表达式匹配文本匹配
- php - SQL Query 选择所有没有订单、姓名、实际地址和电话号码的用户
- python - 当我尝试创建集群时出现错误没有为空集群定义质心
- random - WIN-PROLOG - 如何获得随机值?
- java - 获取 android 8.1.0 的 UI 层次结构 java.lang.reflect.InvocationTargetException 时出现意外错误
- r - 确定整个数据的结构
- java - 在android上使用SQLITE的列约束错误
- javascript - 使用 twitter 登录生成令牌
- reactjs - ES6 map 函数如何在 JSX 中创建对象数组
- c# - 尽管文件存在于 WinForm 中,但 File.Exists 返回 false