【发布时间】:2015-10-08 09:18:45
【问题描述】:
我对 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];
};
非常感谢,抱歉我的英语不好!
【问题讨论】:
-
你为什么不直接加上“latitude = jsonGeo.results[0].geometry.location.lat; longitude = jsonGeo.results[0].geometry.location.lng;”进入你的请求回调函数?
-
你不能那样做。忘记
return继续传递风格;使用回调。 -
我以前做过这个,但它在函数调用时只创建了未定义的结果。
-
@elclanrs:你能给我举个例子吗?谢谢
-
@km65 无论如何,您都可以取消异步功能。例如,使用github.com/abbr/deasync
标签: javascript json node.js asynchronous request