【问题标题】:Use callback response as another function argument使用回调响应作为另一个函数参数
【发布时间】:2015-08-14 05:12:24
【问题描述】:

我正在使用一个地理编码器 API,它在回调中返回结果

data = data ? data : {} // if not given initialize to empty
geocoder.geocode('Kathmandu, Nepal' , function(err, res) {
data.lat = res[0].latitude;
data.lng = res[0].longitude;
});

并使用数据object 构建一个地理点

here = new GeoPoint(here); // data is still {} here

我的问题是如何在上述场景中使用回调响应?

【问题讨论】:

标签: node.js asynchronous callback


【解决方案1】:

geocode 方法是异步的 - 所以你想要对响应做的任何工作都需要在回调中:

geocoder.geocode('Kathmandu, Nepal' , function(err, res) {
    data.lat = res[0].latitude;
    data.lng = res[0].longitude;

    here = new GeoPoint(here); //HAS TO BE IN A CALLBACK 
    //- or passed to another function from within the callback
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2020-10-04
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    相关资源
    最近更新 更多