首页 > 解决方案 > 异步添加后的空字段

问题描述

我正在尝试从文档中获取电子邮件、名字并用我的结果更改另一个字段中的字段,当我在等待之后执行 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
  })

标签: javascript

解决方案


forEach 不能以您期望的方式等待,您必须在一个很好的旧 for 循环中执行它,请参阅此答案: Using async/await with a forEach loop


推荐阅读