Proper way of dealing with forEach Ajax calls in Angular

后端 未结 1 1991
不知归路
不知归路 2021-01-05 08:01

I need to update the data for each object in an array using a for loop and once all the data is captured, run a function. I don\'t want to mix jQuery in this and do it the p

相关标签:
1条回答
  • 2021-01-05 08:22

    The result of your $http(...) call is a promise. This means you can use $q.all to wait for an array of them to complete.

    $scope.updateAllUnits = function(){
        $scope.data = null ; //remove existing data
        var promises = [];
        angular.forEach($scope.units,function(val,key){
          promises.push($scope.getUnitData(val));
        });
        $q.all(promises).then(function success(data){
          console.log($scope.data); // Should all be here
        }, function failure(err){
          // Can handle this is we want
        });
    };
    
    0 讨论(0)
提交回复
热议问题