Ryan Soderberg
Ryan Soderberg

Reputation: 772

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. 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).

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

Upvotes: 0

Views: 29

Answers (1)

Józef Podlecki
Józef Podlecki

Reputation: 11283

Code above can be simplified a bit with 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)

Upvotes: 1

Related Questions