簡體   English   中英

異步代碼和 mongodb 出現問題

[英]Trouble with asynchronous code and mongodb

此代碼搜索一家公司,然后搜索該公司的數組中列出的所有網站,然后搜索該網站上的所有對話,然后搜索每個對話的所有消息,然后將這些 arrays 的消息 ObjectIDs 發送到helper function 然后為每條消息返回一個 JSON 數據數組。 呸..那是一口。

我需要以某種方式等待所有這些完成,然后再清理一下,然后重新發送。 所有代碼都有效,並且console.log(messagesWithData)發布了一些 arrays 消息(因為在這種情況下發送了一些消息)。

感謝所有幫助:)

  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 稍微簡化一下

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