Chetan Kanjani
Chetan Kanjani

Reputation: 85

cannot add data to array because of asynchronous nodejs

api.get('/getfavourites',function(req,res) {


    var userid = req.param('userid');
    array = [];


    User.findById({_id: userid}, function (err, users) {
        if (err) {
            res.send(err);
            return;
        }
        else {



            var i;
            var length = users.favouriteid.length;


            for (i = 0; i < length; i++) {


                var temp = {eid: users.favouriteid[i].eventid};


                Event.findById({_id: temp.eid}, function (err,events) {
                    if (err) {
                        res.send(err);
                        return;
                    }
                    else {

                        array.push(events);


                    }
                });

            }

        }

    });

    console.log(array);

    res.json(array);

});

Because of asynchronous working of nodejs I am not able to get the desired output. array is empty after requesting the get request and where as if use console.log inside the scope of array.push(events) I am able to get the desired output. I tried to solve this problem using callback but I was not able to . I also read about promise object. can you please explain concept of callback and help me solve this problem with the different possible solution. I also used settimeout function and problem was not solved by that also.

how to return data using callbacks and how to use them

Thanks !

Upvotes: 1

Views: 124

Answers (1)

Krzysztof Sztompka
Krzysztof Sztompka

Reputation: 7204

Simplest proposition without use of promises or async module:

api.get('/getfavourites',function(req,res) {
  var userid = req.param('userid');
  array = [];
  User.findById({_id: userid}, function (err, users) {
    if (err) {
      res.send(err);
      return;
     }
     else {
       var i;
       var length = users.favouriteid.length;
       for (i = 0; i < length; i++) {
         var temp = {eid: users.favouriteid[i].eventid};
         Event.findById({_id: temp.eid}, function (err,events) {
           if (err) {
             res.send(err);
             return;
           }
           else {
             array.push(events);
           }
           if(array.length === length){//it is true when all events are pushed
             console.log(array);
             res.json(array);
           }
         });
       }
     }
  });
});

Upvotes: 1

Related Questions