0

I'm not sure why I have to call the getInfo function twice to actually get a value. The first time returns undefined, which I thought the variable would have been set after the JSON.parse. It returns with the actual value if I call the getInfo function again.

var myVariable

exports.getInfo = function(){
  exports.JSONData()
  return myVariable
}

exports.JSONData = function(){
  var req = http.get('JSONFILELINK', function(res){
    var body = ''

    res.on('data', function(chunk){
      body += chunk
    })

    res.on('end', function() {
      var info = JSON.parse(body)
      myVariable = info.my.value
    })
  })
}
Jon
  • 453
  • 5
  • 18
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Amadan Jan 26 '17 at 02:30
  • 2
    `JSONData` is asynchronous: it will finish (and return) way before `myVariable` gets assigned. Presumably, you call it another time from console, or from an event, which allows enough time to pass for the answer to arrive and be processed. A good rule of thumb is - any value you get in an async callback can only ever be used in that async callback; in particular, it can never be returned. Instead of assigning your `info.my.value`, use it right there - or pass a callback into your `JSONData` function, and have it call said callback with `info.my.value` as its parameter. – Amadan Jan 26 '17 at 02:33
  • @Amadan Why not post that as answer? – Farid Nouri Neshat Jan 26 '17 at 02:57
  • @FaridNouriNeshat: Because it is a duplicate, and the linked answer is the canonical one. – Amadan Jan 26 '17 at 03:46

0 Answers0