0

I've created a function that should return a parsed JSON file, but I'm having trouble passing values to a variable.

var getData = function(){
  var parsedData = {};

  var req = http.request(options, function (res){
    var resBody = '';
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
      resBody += chunk;
    });
    res.on('end', function(){
      parsedData = JSON.parse(resBody);
    })
  });
  req.end();
  console.log(parsedData.responseHeader); /* quick test to prove it’s working */
  return parsedData;
}

module.exports = getData;

parsedData was declared outside of the scope of the http.request function, but I can't set a value to it. I can print the value when console.log(parsedData.responseHeader) is in the scope of http.request, but I can't get the value outside of that scope.

Sayuri Mizuguchi
  • 5,250
  • 3
  • 26
  • 53
Narwhal
  • 325
  • 3
  • 15
  • Are you getting an error? Or is it just got being set to the value that you're expecting it to be? – tcigrand Jan 07 '16 at 20:50
  • 2
    Uh, you know that Javascript is asyncronous, right? Callback functions and stuff? You sure have to, before tackling NodeJS. – Jeremy Thille Jan 07 '16 at 20:53
  • That makes a lot more sense. I'll look into asynchronous programming then. Do you have any suggestions on reference material? – Narwhal Jan 07 '16 at 22:18

0 Answers0