【问题标题】:return variable within asynchron function in nodeJS在nodeJS的异步函数中返回变量
【发布时间】: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


【解决方案1】:

不要返回一些东西,而是使用 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]);
});

【讨论】:

  • 感谢您快速而有帮助的回答!这就是解决方案。
  • 这个异步世界真的是一个厄运循环 ;-) 但这样就可以了!谢谢
  • 确实,与其对抗 node.js 的异步特性,不如适应、采用并享受它!
  • @Dirk:我试试看 ;-)
猜你喜欢
  • 2013-09-27
  • 1970-01-01
  • 2015-04-21
  • 2020-01-31
  • 1970-01-01
  • 1970-01-01
  • 2020-06-15
  • 2016-03-11
  • 1970-01-01
相关资源
最近更新 更多