-1

how can I get data from a variable outside of the function? Below is the code, in the comments I put a description of what I mean.

var url = 'http://localhost/cron/temp.php';

request.get({
    url: url,
    json: true,
    headers: {'User-Agent': 'request'}
  }, (err, res, data) => {
    if (err) {
      console.log('Error:', err);
    } else if (res.statusCode !== 200) {
      console.log('Status:', res.statusCode);
    } else {
      // data is already parsed as JSON:
      console.log(data);

      var temp = data; // This var

    }
});


 console.log(temp); // How to get here?


TwitchThis
  • 15
  • 5
  • you can't get it outside of the function, you'll either need to work with it inside your function, use a callback function and pass it as an argument, or use a Promise – Nick Parsons Dec 22 '19 at 12:32
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – dankobgd Dec 22 '19 at 12:51

1 Answers1

0

This will not work

 console.log(temp); // How to get here?

because requesting the data from a site request.get take some time, this is an asynchronous call. We don't know when the request will complete. So the javascript engine starts executing the statement next to request.get which is console.log(temp); // How to get here? and at that time temp has not been defined.

The correct way to do this is create a function that will do the task that you want to do with your data. Like:

const printData = (data) => {
   console.log(data)
}

and call this function inside the callback of request.get. Where you have access to data.

Yogeshwar Singh
  • 519
  • 4
  • 16