0

How do I return data from inside an https.request?

Here is my https request function, which works fine:

var req = https.request(options, (res) => {
  console.log('statusCode: ', res.statusCode);

  res.on('data', (d) => {
    var l = JSON.parse(d);
    console.log(l.firstName);

    //The Retuned JSON is HERE  <—————————————- HERE

  });

});

req.end();

req.on('error', (e) => {
  console.error(e);
});

//What I need is the retuned JSON file here <——————————I NEED IT HERE

I would normally just return some value inside each nested function but with the https.request I am unsure how this works.

Jared Whipple
  • 1,111
  • 3
  • 17
  • 38
  • Call a function which will have `data` as argument.. – Rayon May 01 '16 at 02:43
  • You can't return that data. Why do you need it "there"? – Felix Kling May 01 '16 at 02:55
  • This is part of a single function inside of a function running in node. I need data from the request JSON to post to my DB and for another get request. I guess I could just keep going deeper inside the function, but it seems like it would be cleaner to return the data. – Jared Whipple May 01 '16 at 02:59
  • If you don't want to end up in "callback hell", have a look at promises. – Felix Kling May 01 '16 at 03:21

0 Answers0