我对 NodeJS 及其异步函数有一个小问题。 我需要一个函数,它执行 GET 请求来获取一些 API 数据,然后将一些数据提交回 2 个变量以供函数调用以供进一步使用。 但问题是,我无法使用异步请求函数之外的响应数据来返回一些数据。
有可能实现这一点吗?如果不是,我怎么能做这样的事情?
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 回调来完成必要的任务。
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]);
});
关于javascript - NodeJS 异步函数中的返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31496376/