我有一系列的承诺。
var defered = q.defer();
// promises is a array which will have different promises
var promises = [];
q.all(promises).then(function(response){
// SUSSECCFULLY RESOLVED ALL PROMISE THEN EXECUTION COME HERE
}, function(error){
// IF ANY PROMISE FAILED THEN EXECUTION COME HERE
});
我想处理所有承诺,无论它们失败还是解决。
用例 1:
您希望处理要单独处理的错误,并且所有未调用的错误都成功:
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $q, $timeout) {
function prOne(){
var d = $q.defer();
setTimeout(function(){
d.reject();
}, 100);
return d.promise;
}
function prTwo(){
var d = $q.defer();
setTimeout(function(){
d.resolve();
}, 100);
return d.promise;
}
$q.all([prOne().catch(function(){ console.log('fail for one'); return $q.reject() }), prTwo()]).then(function(){
console.log('success');
return $q.resolve();
}).catch(function(){
console.log('error');
});;
}
myApp.controller('MyCtrl', MyCtrl);
用例 2:
您希望处理要单独处理的错误,并且无论如何都调用成功:
var myApp = angular.module('myApp', []);
function MyCtrl($scope, $q, $timeout) {
function prOne(){
var d = $q.defer();
setTimeout(function(){
d.reject();
}, 100);
return d.promise;
}
function prTwo(){
var d = $q.defer();
setTimeout(function(){
d.resolve();
}, 100);
return d.promise;
}
$q.all([prOne().catch(function(){ console.log('fail for one'); return $q.resolve() }), prTwo()]).then(function(){
console.log('success');
return $q.resolve();
}).catch(function(){
console.log('error');
});;
}
myApp.controller('MyCtrl', MyCtrl);