0

here is my code snippet. I am trying to get details of my friends.friendsList is in reside within the user collection itself and there i am inserting users's id. So first i am fetching userId,then fetching each of their details.but my problem is i am not getting the values of friendsDetails outside the fetchDetailsfunction. I tried many time. i am new to node and sails js. i think its problem of asynchronous execution. How can i solve this problem?

getFriendsDetails:function(req,res){
        var userId = req.param('id');
        var friendsDetails=[];
        User.findOne({
            id: userId
        }).exec(function(err,user){
            var friendsIds=user.friends;
            friendsIds.forEach(function(id){

                User.findOne({
                        id: id
                    }).exec(function fetchDetails(err,Userdetails){

                        var obj={
                            id:Userdetails.id,
                            name:Userdetails.name,
                            pro_pic:Userdetails.profile_pic 
                        }
                        friendsDetails.push(obj);

                        console.log(friendsDetails);//Here consoling pushed data correctly.

                    });
                    console.log(friendsDetails);//here i am getting null array


            });
        });
John Mathew
  • 41
  • 12
  • This is normal behavior. Read a little bit here to find out about basics: https://www.codementor.io/nodejs/tutorial/manage-async-nodejs-callback-example-code – hlozancic Jun 22 '16 at 06:46

1 Answers1

0

As hlozancic said, the behavior is just as expected. The User.findOne queries are asynchronous, so the code continues executing on the line after your callback function, so the console.log(friendsDetails) outside your fetchDetails function is called before any of those on the inside.

As a solution, you don't have to use findOne to search for multiple users; you can use a standard find which returns an array of users based on your search criteria, like this (also using the built-in .then()/.catch() syntax for simplicity's sake):

getFriendsDetails : function(req, res) {
    var userId = req.param('id');
    var friendsDetails = [];
    User.findOne({
        id: userId
    })
    .then(function(user) {
        var friendsIds = user.friends;
        return User.find({
            id: friendsIds
        })
    })
    .then(function(users) {
        users.forEach(function(friend) {
            friendsDetails.push({
                id: friend.id,
                name: friend.name,
                pro_pic: friend.profile_pic                 
            })
        })
        console.log(friendsDetails); // Should log list of friend details
    })
    .catch(function(err) {
        console.log("Error!", err);
    })
}
Fissio
  • 3,748
  • 16
  • 31