0

I have this code in Javascript, using Sails and MongoDB, but the execution of the code is not as I am expecting. The first part of the code is executed at first but the addition to the "foundwaiters" array is executed only at the end (after the logged out case) which is a problem because the array is not updated when the HTML page shows up. How can I fix this ? Thank you.

Tutorial.find(...)
          .populate('videos')
          .exec(function (err, foundTutorials){

            _.each(foundTutorials, function(tutorial){

              _.each(tutorial.videos, function(video){

                User.find().populate('isWaiting').exec(function (err, foundusers){
                  _.each(foundusers, function(user){
                  _.each(user.isWaiting, function(myvideo){
                     if (myvideo.id === video.id ) {
                      foundwaiters.push(user);
                     }
                  });
                });
                });


              });

          });


            // The logged out case
            if (!req.session.userId) {


              return res.view('profile', {
                // This is for the navigation bar
                me: null,

                // This is for profile body
                username: foundUser.username,
                gravatarURL: foundUser.gravatarURL,
                frontEnd: {
                  numOfTutorials: foundTutorials.length,
                  numOfFollowers: foundUser.followers.length,
                  numOfFollowing: foundUser.following.length,
                  /// ###########
                  numOfWaiters:foundwaiters.length
                  // ############
                },
                // This is for the list of tutorials
                tutorials: foundTutorials,
                //   #######
                waiters:foundwaiters
              });
            }
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
E.F
  • 199
  • 1
  • 1
  • 10
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Neil Lunn Jun 21 '17 at 07:43

1 Answers1

0

You could wrap your code with promises. Off-topic, but if this is for Sails, maybe you could drop underscore and use ES2015 or later. You might be able to rewrite your find() to dump of the code, BTW.

Moshe Shmukler
  • 1,270
  • 2
  • 21
  • 43