gpt4 book ai didi

javascript - Angular 链 promise 在第一个之后立即

转载 作者:行者123 更新时间:2023-11-30 12:19:07 25 4
gpt4 key购买 nike

我有两个工厂:getPosition 获取当前位置,geoCoding 使用 google 反向地理编码获取城市名称。他们都使用 $q.defer() 并且他们都将接收到的数据写入本地存储。我想在页面加载时链接它们。因此位置应将当前位置写入本地存储,然后地理编码应立即对其进行解码。我试图像那样链接它们:

   getPosition.get().then(function(geoInfo){
$scope.$storage.geoInfo = geoInfo;
return geoCoding.get().then(function(city){
$scope.$storage.city = city;
$scope.city = $scope.$storage.city;
},function(reason){
alert("Geocoding error: " + reason);
})
}, function(reason){
alert("Location error: " + reason);
});

但这样我只能在初始页面加载时获得位置,在页面刷新时获得城市。我已经阅读了文档并搜索了 stackoverflow,但我仍然遗漏了一些东西。如何链接调用以便在页面加载时接收到它们?

最佳答案

没有测试过,但也许你可以尝试做这样的事情:

getPosition
.get()
.then(function(geoInfo){
$scope.$storage.geoInfo = geoInfo;
return geoCoding.get();
})
.then(function(city){
$scope.$storage.city = city;
$scope.city = $scope.$storage.city;
})
.catch(function(error){
alert("Error: " + error);
});

不确定您是否可以使用 $q 执行此操作,但我已将其与 bluebird 一起使用。在 then() 调用中添加更多的 then() 调用似乎与 promises 的主要好处背道而驰。这与 promise 要防止的回调 hell 一样。所以如果你不能像上面那样把所有的 promise 都串起来,我会感到惊讶。

关于javascript - Angular 链 promise 在第一个之后立即,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31600263/

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