【问题标题】:Retrieving value of inner promise检索内部承诺的价值
【发布时间】:2015-02-16 23:19:24
【问题描述】:

我正在尝试从控制器访问嵌套承诺的值。

这是我的控制器。我正在调用我的服务,希望返回一个城市名称:

LocationService.getCurrentCity(function(response) {
    // This is never executed
    console.log('City name retrieved');
    console.log(response);
});

这里是服务。我正在更新客户的位置,然后我向 Google 请求城市。 console.log(city) 确实按预期记录正确的城市。

this.getCurrentCity = function() {
    return this.updateMyPosition().then(function() {
        return $http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=' + myPosition.lat + ','+ myPosition.lng +'&sensor=false').then(function(response) {
            var city = response.data['results'][0]['address_components'][3]['long_name'];
            console.log(city);
            return city;
        });
    });
}

如何在我的控制器中访问city

【问题讨论】:

    标签: javascript angularjs location promise angular-promise


    【解决方案1】:

    您正在返回一个承诺,应使用then 解开它:

    LocationService.getCurrentCity().then(function(response) {
        // This is never executed
        console.log('City name retrieved');
        console.log(response);
    });
    

    Promises 通过使用返回值来工作,就像同步值一样 - 当您调用 getCurrentCity 时,它会返回一个您可以使用 then 解包的 Promise。

    【讨论】:

    • @Maeh 不客气 - 不强制执行函数采用的参数数量是 JS 的一个烦人的属性。一个好的静态分析工具真的可以在发现这些烦人的错误方面大有帮助。
    猜你喜欢
    • 1970-01-01
    • 2017-12-22
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多