1

I am doing very simple requests to take some data from MongoDB and then send them to my views

router.get('/', isAuthenticated, function(req, res) {
    Conversation.findAllConversation(req.user._id, function(err, data) {
        if (err) return console.error(err); // handle this

        var array = [];

        data.forEach(function (element, index, array){
            ConversationReply.findLastReply(element._id, function(err, replys) {
                if(err) return cosole.log(err);
                console.log(replys);
                array.push(replys);
            });
        });

        console.log(array);

        res.render('messages/index', {
          title : 'Messages', 
          conversations: data,
          user: req.user, 
          lastReplys: array });
   });
});

But all data from replys is not pushing to my array and then just sending empty. Console.log(replys) showing me all my replys correctly.

user256968
  • 371
  • 1
  • 5
  • 18

1 Answers1

1

findLastReply is returning asynchronously, while the request function is proceeding synchronously. To fix this, I would do something like this:

router.get('/', isAuthenticated, function(req, res) {
    Conversation.findAllConversation(req.user._id, function(err, data) {
        if (err) return console.error(err); // handle this

        var array = [];

        data.forEach(function (element, index, array){
            ConversationReply.findLastReply(element._id, function(err, replys) {
                if(err) return cosole.log(err);
                console.log(replys);
                array.push(replys);

                if (array.length === data.length) {
                  // we are done! :D
                  console.log(array);

                  res.render('messages/index', {
                    title : 'Messages', 
                    conversations: data,
                    user: req.user, 
                    lastReplys: array });
                }
            });
        });
   });
});

Even better is to use Promises, but this is not required.

Matthew King
  • 1,342
  • 7
  • 13