在nodeJS中的异步函数中返回变量

时间:2015-07-18 23:00:40

标签: javascript json node.js asynchronous request

我对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];    
};

非常感谢,抱歉我的英语不好!

1 个答案:

答案 0 :(得分: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]);
});
相关问题