简体   繁体   中英

nodejs calling a variable outside of a scope

I am working with nodejs and in the JS file i have the code below to retrieve data . when i try to use the data outside the scope it doesn't work i get the content undefined the whloe time ..

var data = {};
request.get({url: 'https://my-host/Mypath'}, function(err, response, body) {


  if (err) {
      console.error(err);
      data.err = err;
  }

  data= body;


});
console.log('Data: ', data);

My main problem is that i have to send res.render with the data and i need to do multiple requests to the server .

You are making an async call. console.log() is executed before the request. Try moving that console.log into the request callback and it will work.

To use it out of the request function, you need to return a promise. Maybe try the Q tool: https://github.com/kriskowal/q

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM