AngularJS: $q wait for all even when 1 rejected

后端 未结 8 1601
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 16:23

I\'ve been trying to wait for a couple of promises with Angular\'s $q but there seems to be no option to \'wait for all even when a promis is rejected\'. I\'ve created an exampl

8条回答
  •  佛祖请我去吃肉
    2021-02-01 16:55

    Thanks for the inspiration Zenuka, you can find my version at https://gist.github.com/JGarrido/8100714

    Here it is, in it's current state:

    .config( function($provide) {
      $provide.decorator("$q", ["$delegate", function($delegate) {
        var $q = $delegate;
    
        $q.allComplete = function(promises) {
    
          if(!angular.isArray(promises)) {
            throw Error("$q.allComplete only accepts an array.");
          }
    
          var deferred = $q.defer();
          var passed = 0;
          var failed = 0;
          var responses = [];
    
          angular.forEach(promises, function(promise, index) {
            promise
              .then( function(result) {
                console.info('done', result);
                passed++;
                responses.push(result);
              })
              .catch( function(result) {
                console.error('err', result);
                failed++;
                responses.push(result);
              })
              .finally( function() {
                if((passed + failed) == promises.length) {
                  console.log("COMPLETE: " + "passed = " + passed + ", failed = " + failed);
    
                  if(failed > 0) {
                    deferred.reject(responses);
                  } else {
                    deferred.resolve(responses);
                  }
                }
              })
            ;
          });
    
          return deferred.promise;
    
        };
    
        return $q;
      }]);
    })
    

提交回复
热议问题