javascript - NodeJS 异步函数中的返回变量

标签 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];    
};

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

最佳答案

不要返回某些内容,而是使用 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/

相关文章:

javascript - 多个音频 html : auto stop other when current is playing with javascript

javascript - 如何检查文本覆盖图像的百分比?

javascript - 在数据库中的循环 (for) 中插入值时出现问题 : same value is inserted - node js/sql

javascript - 检查数组的更多元素是否具有相同的 key 值,是否删除了一个?

javascript - 如何使用 document.cookie 来存储和检索数组中的值?

json - 尝试使用 json 验证 gcloud 时出错

java - 从 Solr 中检索对象

javascript - 在 Node.js 中解析 Json,其中将数字作为其关键参数

node.js - 在 Nodejs 缓冲区中写入位

macos - 在 mac os x 上使用 boot2docker 运行 docker?