0

I try to store the result of a DB query in an array but I always got an empty array. I don't understand very well how Async works but I think this code should be work because I store The variable before It finish

Note: following is an array also.

code:

    exports.getfollowingUser = function(req, res){
  followedUser=[];
  following = req.user.follow;

  for (i = 0; i < following.length; i++) { 
    User.find(following[i].followed, function (err, followUser){
    followedUser[i]= followUser;
    });
    }
    console.log(followedUser) // result empty
    res.render('following', {
      followedUser: followedUser 
    });
  };
Vikash Chauhan
  • 792
  • 2
  • 9
  • 18
Jose Osorio
  • 911
  • 2
  • 12
  • 25
  • JohnnyHK could you explain me please ? – Jose Osorio Jan 09 '15 at 21:56
  • There are great answers in the linked duplicate that describe the issue in detail. In short, your `for` loop completes and the code continues on to the `console.log` line before any of the `user.find` callbacks occur so `followedUser` isn't modified yet. Your confusion is natural, as async is hard to wrap your head around. Take some time to read and understand those answers, it should really help. – JohnnyHK Jan 09 '15 at 22:03
  • @JohnnyHK I read the other answer but i can't get it because i don't know other way to store the data :S – Jose Osorio Jan 09 '15 at 22:11

0 Answers0