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?