正在检索内部承诺的值
Retrieving value of inner promise
我正试图从控制器访问嵌套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。
相关文章:
- 内部分区字体大小获胜'调整浏览器窗口大小时不会随媒体查询而更改
- 我的职位回报太快了,如何做出承诺
- 打破承诺链的好方法是什么
- 从函数返回角度承诺
- 调用函数内部的函数
- 如何使用js将SNAPSHOT内部版本号转换为3位数的整数
- 在phonegap应用程序内部重定向不起作用
- 使用此选项选择父类内部的类
- 承诺内部工作
- 正在检索内部承诺的值
- JQuery 承诺:访问外部变量或将结果传递给 .done 内部的 IIFE
- 如何获取 Ember 组件对象内部承诺成功或错误回调
- Ember.RSVP.hash 重新加载内部承诺
- Do量角器's期望在内部等待承诺
- 将键/值附加到承诺内部的对象
- 单元测试:测试内部承诺
- 内部的Web工作者承诺导致崩溃
- 从承诺链内部解析是安全的
- 承诺链在内部承诺被解决之前继续
- 我是否应该改变一个已承诺并已解决的值的内部状态