簡體   English   中英

Angular JS中的鏈接promise的問題

[英]Issue in chaining promises in Angular JS

我有一個邏輯問題。

我在localStorage有一個對象數組。 我想要做的是,對每個人都有效地進行API調用,然后將新項推route to a new component 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"]);    
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM