return nodeJS 异步函数中的变量
return variable within asynchron function in nodeJS
我对 nodeJS 及其异步函数有一些小问题。
我需要一个函数,它执行 GET 请求以获取一些 API 数据,然后将一些数据提交回 2 个变量以供函数调用以供进一步使用。
但问题是,我无法将异步请求函数之外的响应数据用于 return 某些数据。
有没有可能实现?如果不是我怎么能做那样的事情?
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]);
});
我对 nodeJS 及其异步函数有一些小问题。 我需要一个函数,它执行 GET 请求以获取一些 API 数据,然后将一些数据提交回 2 个变量以供函数调用以供进一步使用。 但问题是,我无法将异步请求函数之外的响应数据用于 return 某些数据。
有没有可能实现?如果不是我怎么能做那样的事情?
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]);
});