【问题标题】:JavaScript async/await not working as expected [duplicate]JavaScript异步/等待未按预期工作[重复]
【发布时间】:2021-12-08 06:11:02
【问题描述】:

我正在使用async/await,但它没有按预期工作。在解决承诺之前正在更新数据。

export const update = async (req, res) => {
let lead = Lead.findbyid(id)
let updates = req.body.updates
if (updates.clientDetails.alternateContacts && updates.clientDetails.alternateContacts.length > 0) {
      updates.clientDetails.alternateContacts.forEach(async ele => {
        if (ele.addedOn) console.log('date exists')
        else ele.addedOn = new Date()

        if (ele.email) {
          console.log('11111111111111111111');
          let clientId = await createAutoAccount({ email: ele.email, name:ele.name, contactNumber: ele.phoneNumber })
          console.log('22222222222222222222222', clientId);
          ele.userId = clientId
        }
      })
      lead.clientDetails.alternateContacts = updates.clientDetails.alternateContacts
    }

await lead.save();
}
export const createAutoAccount = async (data) => {
let user = await User.findOne({ email: data.email });
    if (user) {
      console.log('user found =======================', user._id);
    } else {
      console.log('new user created ---------------');
      const tempObj = {
        email: data.email,
        password: data.password ? data.password : 'user123',
        full_name: data.name ? data.name : null,
        contact_number: data.contactNumber && !isNaN(data.contactNumber) ? data.contactNumber : null,
      };
      user = await User.create(tempObj);
    }

    return user._id;
}

输出顺序为:

11111111111111111111 

update lead

user found ======================= 617155c8827ab456041342ad

22222222222222222222222 617155c8827ab456041342ad

想要的是:

11111111111111111111 

user found ======================= 617155c8827ab456041342ad

22222222222222222222222 617155c8827ab456041342ad

update lead

请让我知道需要修改哪些内容才能使这项工作符合预期。

【问题讨论】:

  • 你在哪里输出“更新线索”?
  • @Taxel by "update lead",我的意思是lead.save()
  • 你需要for (const ele of updates.clientDetails.alternateContacts) { /*...*/ } 而不是updates.clientDetails.alternateContacts.forEach(async ele => { /*...*/ })
  • @CherryDT 是的,它成功了!
  • 顺便说一句,它应该是“findById”而不是“findbyid”。我想知道如果不纠正这个问题,它是如何工作的。

标签: javascript node.js asynchronous async-await


【解决方案1】:

我没有足够的代表发表评论,所以这应该是评论,但请看这篇文章。

Using async/await with a forEach loop

据我所知,您的问题是由于您尝试在 foreach 循环中使用异步等待。我过去曾遇到过这样的问题。

【讨论】:

    【解决方案2】:

    我找不到update lead 日志的来源。但我认为它应该来自lead.save()。如果是,问题应该是forEach循环的async回调。

    updates.clientDetails.alternateContacts.forEach(async ele => { ... })
    

    当你使用forEach 方法时,它接受一个回调。 for each 方法中的await,以下仅适用于callback

    if (ele.addedOn) console.log('date exists')
            else ele.addedOn = new Date()
    
            if (ele.email) {
              console.log('11111111111111111111');
              let clientId = await createAutoAccount({ email: ele.email, name:ele.name, contactNumber: ele.phoneNumber })
              console.log('22222222222222222222222', clientId);
              ele.userId = clientId
            }
          })
          lead.clientDetails.alternateContacts = updates.clientDetails.alternateContacts
    

    通过更改为以下代码,尝试将await 执行上下文设置为update 函数,而不是forEachcallback

    export const update = async (req, res) => {
    let lead = Lead.findbyid(id)
    let updates = req.body.updates
    if (updates.clientDetails.alternateContacts && updates.clientDetails.alternateContacts.length > 0) {
          // Use normal for loop instead of forEach with callback, the execution context will be the update function
          for(const alternateContracts of updates.clientDetails.alternateContacts) {
            if (ele.addedOn) console.log('date exists')
            else ele.addedOn = new Date()
    
            if (ele.email) {
              console.log('11111111111111111111');
              let clientId = await createAutoAccount({ email: ele.email, name:ele.name, contactNumber: ele.phoneNumber })
              console.log('22222222222222222222222', clientId);
              ele.userId = clientId
            }
          })
          lead.clientDetails.alternateContacts = updates.clientDetails.alternateContacts
        }
    
    await lead.save();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 2019-04-19
      • 2020-03-04
      • 2019-04-07
      • 2018-05-05
      • 2022-01-22
      • 1970-01-01
      • 2021-07-15
      • 2023-03-03
      相关资源
      最近更新 更多