0

I am making a call to an API which will return the json object. The json object is stored in a variable.I am trying to print the part of the json object on console. But, I am not able to load the data to console once i exit the request{} loop. How do I make this work? How do I make the variable global? I am using the following Node js script. const request = require('request');

var explanation;
request('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }, (err, res, body) => {
  if (err) { return console.log(err); }
  console.log(body.url);
explanation = body.explanation;
  console.log(body.explanation);

});
console.log(explanation);

The console read : undefined

I think it have to make the explanation variable global. How do i do that? Is there any better way to do the above mentioned thing?

user45437
  • 183
  • 3
  • 15
  • The request is asynchronous, so the variable isn't going to be set until the request finishes. But you're logging the variable synchronously, so that last `console.log` will ALWAYS give you `undefined`. Code that relies on the result of your request has to go inside the callback, or you need to switch to using promises. Either way, you have to understand and embrace the asynchronous nature of javascript. – CRice Oct 30 '17 at 23:43
  • You DON'T use the value outside the callback. Put your `console.log(body.explanation)` INSIDE the callback and all will be well. Also put any code in there that will use that value. This is how asynchronous programming works in Javascript. – jfriend00 Oct 30 '17 at 23:49
  • I got you. It was of great help. – user45437 Oct 31 '17 at 00:06

1 Answers1

0

well, the console.log will just print undefined because it was executed right after request is sent but not waiting for the response to come back (not blocking). however, it does indeed will update the explanation variable.

to check this, say if the request takes 1 seconds, you can use setTimeout 2000ms then console.log it.

Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54
  • I don't think that is the issue, because when I log data to console before closing the request loop, it works perfectly. So console.log(explanation) }); works fine . But }); console.log(explanantion) pprints undefined – user45437 Oct 31 '17 at 00:00
  • if you have a loop, the variable probably shows the content set from the previous iteration. – Tuan Anh Tran Oct 31 '17 at 00:02
  • I got you, It worked. Thanks :) – user45437 Oct 31 '17 at 00:06