【问题标题】:Trouble with asynchronous code and mongodb异步代码和mongodb的问题
【发布时间】:2020-07-26 11:49:31
【问题描述】:

此代码搜索一家公司,然后搜索该公司数组中列出的所有网站,然后搜索该网站上的所有对话,然后搜索每个对话的所有消息,然后发送这些消息数组helper 函数的 ObjectID,然后该函数返回每个消息的 JSON 数据数组。呸..那是一口。

我需要以某种方式等待所有这些完成,然后再清理一下,然后重新发送。所有代码都有效,console.log(messagesWithData) 发布了一些消息数组(因为在这种情况下发送了一些消息)。

感谢所有帮助:)

  Company.findOne({ 'roles.admins': userId }, function (err, doc) {
    if (!err) {
      for (const item of doc.websites) {
        Website.findById(item, function (err, doc) {
          for (const item of doc.conversations) {
            Conversation.findById(item, function (err, doc) {
              async function findMessageData() {
                var messagesWithData = await helper.takeMessageArray(
                  doc.messages
                );
                await sendMessages(messagesWithData);
              }
              findMessageData();

              async function sendMessages(messagesWithData) {
                // not sure what to put here!
                console.log(messagesWithData)
              }
            });
          }
        });
      }
    } else {
      res.send(err);
    }
  });

【问题讨论】:

  • 如果你想使用async/await,不要向mongodb传递任何回调,而是使用它返回的promise。

标签: javascript mongodb asynchronous mongoose async-await


【解决方案1】:

上面的代码可以用 async/await 稍微简化一下

const company = await Company.findOne({ 'roles.admins': userId });
let allMessages = []
for (const websiteId of company.websites) {
    const website = await Website.findById(websiteId);

    for (const conversationId of website.conversations) {
        const conversation = await Conversation.findById(conversationId);
        const messagesWithData = await helper.takeMessageArray(
            conversation.messages
        );
        allMessages = [...allMessages, ...messagesWithData]
    }
}
// Everything completed, messages stored in one place...
console.log(allMessages)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2018-04-30
    • 2019-11-05
    • 2022-01-22
    相关资源
    最近更新 更多