1

Basically what I am trying to accomplish is to take the results from the handleMusicAPICalls function and push it into the results array, which was declared in the callback function for the get route. Currently when I run this, the fist output is "[]" (from the 2nd console.log) and then under it is the actual data I want to see (first console.log). Any advice?

router.get("/activities", middleware.isLoggedIn, function(req, res) {
  var destination = req.query.destination;
  var startDate = req.query.daterange.replace(/\s+/g, '').split("to")[0];
  var endDate = req.query.daterange.replace(/\s+/g, '').split("to")[1];
  var activities =  req.query.activities;
  var results = [];

  helper.handleMusicAPICalls(destination, startDate, endDate, activities, function(res) {
    console.log(res);
    results.concat(res);
  });
  console.log(results);
});
dev
  • 11
  • 4
  • 1
    That's how async works. Try Googling how to work with asynchronous operation in js – Shivam Jun 27 '17 at 18:42
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Shivam Jun 27 '17 at 18:49

1 Answers1

1

your handleMusicAPICalls executes immediately with all the arguments including the handler callback (the last argument), but that callback doesn't get called immediately.

and then the next line to handleMusicAPICalls is your console.log(results);

so as of now it is empty as no one modified it. and then when ever the event occur (it is true for any event), the event callback getting executed asynchronously, and then these two lines get executed

console.log(res); results.concat(res);

it still has a access to result because of it has accessed to the outer variable as it its created a closure env, so you are able to modify that, and you are logging it.

Hope it helps.

Koushik Chatterjee
  • 4,106
  • 3
  • 18
  • 32