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);
});
2

1 Answer 1

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.

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.