AngularJS:$q等待所有即使1拒绝

前端之家收集整理的这篇文章主要介绍了AngularJS:$q等待所有即使1拒绝前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在试图等待几个承诺与Angular的$ q,但似乎没有选择“等待所有即使promis被拒绝”。
我创建了一个例子( http://jsfiddle.net/Zenuka/pHEf9/21/),我想要一个函数执行时,所有的promise解决/拒绝,是可能吗?
就像是:
$q.whenAllComplete(promises,function() {....})

编辑:在该示例中,您看到第二个服务失败,然后立即执行$ q.all()。then(…,function(){…})中的函数。我想等待第五个承诺完成。

好的,我自己实现了一个基本的版本(我只想等待一个promise数组)。任何人都可以扩展这个或创建一个更干净的版本,如果他们想:-)
检查jsfiddle看到它在行动: http://jsfiddle.net/Zenuka/pHEf9/
angular.module('test').config(['$provide',function ($provide) {
    $provide.decorator('$q',['$delegate',function ($delegate) {
        var $q = $delegate;

        // Extention for q
        $q.allSettled = $q.allSettled || function (promises) {
            var deferred = $q.defer();
            if (angular.isArray(promises)) {
                var states = [];
                var results = [];
                var didAPromiseFail = false;
                if (promises.length === 0) { 
                    deferred.resolve(results);
                    return;
                }

                // First create an array for all promises with their state
                angular.forEach(promises,function (promise,key) {
                    states[key] = false;
                });

                // Helper to check if all states are finished
                var checkStates = function (states,results,deferred,Failed) {
                    var allFinished = true;
                    angular.forEach(states,function (state,key) {
                        if (!state) {
                            allFinished = false;
                        }
                    });
                    if (allFinished) {
                        if (Failed) {
                            deferred.reject(results);
                        } else {
                            deferred.resolve(results);
                        }
                    }
                }

                // Loop through the promises
                // a second loop to be sure that checkStates is called when all states are set to false first
                angular.forEach(promises,key) {
                    $q.when(promise).then(function (result) {
                        states[key] = true;
                        results[key] = result;
                        checkStates(states,didAPromiseFail);
                    },function (reason) {
                        states[key] = true;
                        results[key] = reason;
                        didAPromiseFail = true;
                        checkStates(states,didAPromiseFail);
                    });
                });
            } else {
                throw 'allSettled can only handle an array of promises (for now)';
            }

            return deferred.promise;
        };

        return $q;
    }]);
}]);
原文链接:https://www.f2er.com/angularjs/145167.html

猜你在找的Angularjs相关文章