正在检索内部承诺的值

Retrieving value of inner promise

本文关键字:承诺 内部 检索      更新时间:2023-12-06

我正试图从控制器访问嵌套promise的值。

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

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

这是服务。我正在更新客户的位置,然后我向谷歌请求城市。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

您正在返回一个promise,应该使用then:打开它

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

promise的工作原理是使用返回值,就像使用同步值一样——当您调用getCurrentCity时,它会返回一个可以使用then打开的promise。