简体   繁体   English

异步代码和 mongodb 出现问题

[英]Trouble with asynchronous code and mongodb

This code searches for a company then searches for all of the websites listed in an array on that company, then searches for all the conversations on that website, then searches for all the messages for each conversation, then sends those arrays of message ObjectIDs to the helper function which then returns an array of JSON data for each message.此代码搜索一家公司,然后搜索该公司的数组中列出的所有网站,然后搜索该网站上的所有对话,然后搜索每个对话的所有消息,然后将这些 arrays 的消息 ObjectIDs 发送到helper function 然后为每条消息返回一个 JSON 数据数组。 Fhew.. that was a mouthful.呸..那是一口。

I need to somehow wait for all of this to complete before cleaning it up a bit then res.send'ing it.我需要以某种方式等待所有这些完成,然后再清理一下,然后重新发送。 All of the code works and the console.log(messagesWithData) posts a few arrays of messages (since it is sent a few in this scenario).所有代码都有效,并且console.log(messagesWithData)发布了一些 arrays 消息(因为在这种情况下发送了一些消息)。

All help is appreciated:)感谢所有帮助:)

  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);
    }
  });

Code above can be simplified a bit with async/await上面的代码可以用 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM