gpt4 book ai didi

javascript - 检索内在 promise 的值(value)

转载 作者:行者123 更新时间:2023-11-30 17:02:48 25 4
gpt4 key购买 nike

我正在尝试从 Controller 访问嵌套 promise 的值。

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

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;
});
});
}

如何在我的 Controller 中访问城市

最佳答案

你正在返回一个 promise ,应该用 then 解包:

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

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

关于javascript - 检索内在 promise 的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com