0

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?

Community
  • 1
  • 1
patrickhuang94
  • 2,085
  • 5
  • 36
  • 58
  • 1
    And yes, you are doing an async call. – tcooc Oct 13 '16 at 20:29
  • I resolved it by passing the API call inside the callback. Thanks! – patrickhuang94 Oct 13 '16 at 21:00
  • 1
    You don't store it in a variable. You use it where you have it in the callback. Your server can serve many requests from many clients, some of them even running at the same time. You can't store data from one request into a global or module-scoped variable because that allows multiple requests to clobber each other. Instead, you use the data where you have it. – jfriend00 Oct 14 '16 at 01:22
  • @jfriend00 Yup, I understand it now. Thanks for clarifying it – patrickhuang94 Oct 14 '16 at 03:06

0 Answers0