I've looked at several SO posts regarding asynchronicity in HTTP requests. Specifically, I'm referring to this post: How to get data out of a Node.js http get request
I want to parse JSON and store that parsed data into a variable which is to be accessed later in an API call. This is a GET
request.
var name = "";
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(res) {
var responses = [];
res.setEncoding('utf8');
res.on('data', function(response) {
responses.push(response);
});
res.on('end', function() {
name = JSON.parse(responses.join("")).name;
console.log(name); //Prints out 'Sam'
});
}
var req = https.request(options, callback).end();
console.log(name) //logs undefined
Is what I'm doing an asynchronous call? How do I retrieve the information in the HTTP request and store it into a variable properly?