多查询以及如何等待最后一个查询做某事?

Multi query and how to wait up last query an do smth?

我有查询周期:

angular.forEach(checkeds, function(item, i){
  updateData({id: Math.floor(item.id), prcn: item.value });
});

我需要在最后一次查询后执行函数:

function updateData(model) {
   clientService.updateOptimizable(model).then(function(response){
     if(lastQuery){
       read(); // maybe like this
     }
  }
}

           
            

求助,我有这么多信息、承诺、$q 服务、队列,我很困惑,不知道如何正确地做到这一点

// let set a flag to monitor our last item in the loop
var flag = false;
angular.forEach(checkeds, function(item, i){
   if(i == checkeds.length - 1){
      flag = true;
      updateData({id: Math.floor(item.id), prcn: item.value });
   }
});


function updateData(model) {
   clientService.updateOptimizable(model).then(function(response){
     // if flag is true then do something
     if(flag == true){
        read(); // maybe like this
     }
   }
}

您可以使用 $q.

jsfiddle.

上的实例

angular.module('ExampleApp', [])
  .controller('ExampleController', function($scope, $q, $timeout) {
    $scope.checkeds = [1, 2, 1, 2, 1, 3, 1];

    function updateData(val,ind) {
      //simulate call server-side $http.post that return $promise
      var defered = $q.defer();
      $timeout(function() {
        console.log('executed', val, 'index', ind);
        defered.resolve();
      }, val * 1000);
      // in your case, you need return clientService.updateOptimizable(model);
      return defered.promise;
    }
    $scope.start = function() {
      $scope.promises = [];
      angular.forEach($scope.checkeds, function(item, i) {
        $scope.promises.push(updateData(item, i));
      });
      $q.all($scope.promises).then(function() { // this invoke, then ALL updateData is resolve (finished)
        console.log('ALL executed');
      });
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">
    <form name="testForm">
      <button ng-click="start()">
        start
      </button>
    </form>
  </div>
</div>