1
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 !

1 Answer 1

1

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);
           }
         });
       }
     }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.