0

I have the below code where I have declared the array var filteredArray = [];. I make use filteredArray to push data in the callback function of a Rest call(This happens inside a for loop). Once the for loop ends. I want to send the filteredArray to my angular controller. Here is my code. When I put console.log(filteredArray) outside the for loop, I get an empty array. Can someone please help?

assignedToMe: function(req, res) {
  CustomerUser.find({
    userEmail: {
      $in: req.body.userEmail
    }
  }, function(err, docs) {

    var filteredArray = [];
    for (var i = 0; i < docs.length; i++) {
      var url = config.pythiaApi + config.pythiaApiPrefix + '/quotes/' + docs[i]['quoteId'];
      if (req.originalUrl.lastIndexOf('?') !== -1) {
        url += req.originalUrl.substr(req.originalUrl.lastIndexOf('?'));
      }
      restClient.get(url, function(body, response) {
        filteredArray.push(body.data)
      })
    }

    console.log(filteredArray) // Gives empty array
    res.status(200).json({});

  });
}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
JaRavi
  • 71
  • 3

1 Answers1

1

Use asyncronous loop for async calls. For example async.times

assignedToMe: function(req, res) {
    CustomerUser.find({
        userEmail: {$in: req.body.userEmail}
    }, function(err, docs) {
        var filteredArray = [];
        async.times(docs.length, function(i, next){
            if(err) return next(err);
            var url = config.pythiaApi + config.pythiaApiPrefix + '/quotes/'+docs[i]['quoteId'];
            if (req.originalUrl.lastIndexOf('?') !== -1) {
                url += req.originalUrl.substr(req.originalUrl.lastIndexOf('?'));
            }
            restClient.get(url, function (body, response) {
                next(null, body.data)
            })
        }, function(err, result){
            // result contains your array
            res.status(200).json({});
        })
    });
}
Vladimir G.
  • 885
  • 7
  • 15