-1

So I'm fairly new to node js, and am having trouble wrapping my head around asynchronous programming. I'm trying to get a JSON from a website and pass it to a variable for use later, to test I have been using this code:

var https = require("https");
var a;
function getter(url){
  var request = https.get(url, function(response){
    var body = "";
    response.on("data", function(chunk){
      body += chunk;
    });
    response.on("end", function(){
      if(response.statusCode === 200){
        try{
          a = JSON.parse(body);
        }catch(err){
          console.log(err);
        }
      }
   })
 })
};
getter('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY');
console.log(a);

When I run this I get a as undefined, which seems to make sense from what I've read. But I'm unclear as to what to do from here. How would I go about passing this JSON into a variable?

  • 1
    just move your `console.log` inside the response on-end, and you should get your results displayed – David784 Jul 13 '18 at 21:21
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Denis Jul 13 '18 at 21:29
  • Check this question: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 – Denis Jul 13 '18 at 21:29

1 Answers1

0

http.get is asynchronous and executes the event handlers when the events occur. When you call getter() this function immediately returns, ie it does not wait for the events and the next statement console.log(a) is executed.

Furthermore, js is single threaded, and the current execution stack is never interrupted for any other event/callback or whatsoever. So the event handlers can only run if the current execution has come to an end, ie contains noch more statements. Thus, your console.log() will always be executed before any eventhandler of the request, thus a is still undefined.

If you want to continue after the request finished, you have to do it from the eventhandler.

See this excellent presentation for some more details https://youtu.be/8aGhZQkoFbQ

derpirscher
  • 14,418
  • 3
  • 18
  • 35