在nodeJS中的asynchronous函数内返回variables

我有一个nodeJS和他们的asynchronous函数有点问题。 我需要一个GET请求获取一些API数据,然后提交一些数据返回到2个variables函数调用进一步使用的函数。 但问题是,我不能使用asynchronous请求函数外的响应数据来返回一些数据。

有没有可能意识到这一点? 如果不是,我该怎么做呢?

var geoData = function(address){ // Google API Key apikey = 'XXX'; // google API URL for geocoding var urlText = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address)+'&key=' + apikey; request(urlText, function (error, response, body) { if (!error && response.statusCode == 200) jsonGeo = JSON.parse(body); console.log(jsonGeo.results[0].geometry.location); } }) // Variable jsonGeo isn't declared here latitude = jsonGeo.results[0].geometry.location.lat; longitude = jsonGeo.results[0].geometry.location.lng; return [latitude,longitude]; }; 

非常感谢,为我的英语不好而感到遗憾!

而不是返回的东西使用geoData的callback,这将做必要的任务。

 var geoData = function(address, callback){ // Google API Key apikey = 'XXX'; // google API URL for geocoding var urlText = 'https://maps.googleapis.com/maps/api/geocode/json?address='+encodeURIComponent(address)+'&key='+apikey; request(urlText, function (error, response, body) { if (!error && response.statusCode == 200) { jsonGeo = JSON.parse(body); console.log(jsonGeo.results[0].geometry.location); latitude = jsonGeo.results[0].geometry.location.lat; longitude = jsonGeo.results[0].geometry.location.lng; callback([latitude,longitude]); } }) }; 

像这样使用它

 geoData('myaddress', function(arr){ console.log(arr[0], arr[1]); });