1

I am working on a chat application. I have chat history in chats table. Now I want to see the latest message of each chat by using the sender email. So, I am getting the chat id by using distinct query as shown below

var userChat = [];
Chat.distinct("chatId", {"senderEmail" : req.params.Email}, function(err, result){
  if( result){
    console.log(result);

    for(var i = 0; i < result.length; i++){
      Chat.find({ chatId: result[i] }).sort('-_id').limit(1).exec(function(error, result) 
        {
        if(result){
          console.log(" IN FOR LOOP ");
          userChat.push(result);
        }
      });
    }  

    console.log("USER CHAT ARRAY :  ", userChat);

  }

});

After running the distinct query I got 4 chat ids [ '114143', '130997', '457884', '479310' ]

Now the problem is that whenever I call push then it is not pushing result array from find query into the userChat array. Also I have noticed that the console of USER CHAT ARRAY is called BEFORE for loop console. Following is the screenshot of the console

enter image description here

1 Answer 1

1

Each Chat.find() operation is asynchronous, so your for loop creates and finished the iteration. By the time you hit console.log("USER CHAT ARRAY : ", userChat); none of this operations has finished yet.

Thats by you see USER CHAT ARRAY: [] and then IN FOR LOOP on the console.

You need to await each of this Chat.find() operations like so:

Chat.distinct("chatId", {"senderEmail" : req.params.Email}, async function(err, result){
  if( result){
    console.log(result);

    for(var i = 0; i < result.length; i++){
      try {
        var chat = await Chat.find({ chatId: result[i] }).sort('-_id').limit(1).exec();
        if(chat){
          console.log(" IN FOR LOOP ");
          userChat.push(chat);
        }
      } catch (e) {
        //Handle errors here
      }
    }  
    console.log("USER CHAT ARRAY :  ", userChat);
  }
});

The changes:

  1. Mark Chat.distinct callback function with async
  2. In for loop, await each Chat.find() query
  3. Use try/catch to handle errors
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for explaining. I tried it and I got a result in USER CHAT ARRAY but for chat id which is on index 0. It did not return the find result for chat ids that are on index 1 to 3.
sorry I made a mistake, I use the result variable inside the for loop and has the same name as the variable from outside. I will change it to chat

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.