我有一个逻辑问题。
我在 localStorage
中有一个对象数组。我想要做的是,他们每个人都有效地进行 API 调用,然后将新项目推送到 localStorage
中,一旦一切都完成,然后只 route to a new component
.
if(migrationName){
angular.forEach(JSON.parse($window.localStorage.selectedItems), function(item) {
var url = '/api/get_all_prices/'+item.details.id+'/us-1';
HttpWrapper.send(url,{"operation":'GET'}).then(function(pricingOptions){
item.selectedMapping = pricingOptions[0];
vm.selectedItems[type].push(item); // Store it in a variable first
$window.localStorage.setItem('selectedItems',JSON.stringify(item));
});
});
$rootRouter.navigate(["MigrationRecommendation"]); // Route once everything is done
}
我知道这是错误的。
我每次都在循环中设置 localStorage,而且我不会在数组中的所有内容都完成后只处理路由。
如何改变逻辑?
最佳答案
您应该将 $q.all 与使用 Array.prototype.map 创建的 promise 数组一起使用:
var items = JSON.parse($window.localStorage.selectedItems)
var promises = items.map(function(item) {
var url = '/api/get_all_prices/' + item.details.id + '/us-1';
return HttpWrapper.send(url, {"operation": 'GET'}).then(function(pricingOptions) {
item.selectedMapping = pricingOptions[0];
vm.selectedItems[type].push(item); // Store it in a variable first
$window.localStorage.setItem('selectedItems', JSON.stringify(item));
});
});
$q.all(promises).then(function() {
$rootRouter.navigate(["MigrationRecommendation"]);
})
关于javascript - Angular JS 中的链式 promise 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44023512/