AngularJS按异常处理顺序$q服务响应



我有一个函数,它使用for循环的承诺为异步调用提供顺序响应,但当我从代码中得到异常时循环中断,但我想继续我的循环即使在函数抛出异常之后。

我的异步函数是

function asyncFun(a) { 
var q = $q.defer(); 
setTimeout(function(){
if(a == 4) throw new Error('custom error'); 
q.resolve(a);
}, 1000); 
return q.promise; 
}

和链功能是

function getData() {
var chain = $q.when();
for (var i = 0; i < 10; i++) {
(function(i) {
chain = chain.then(function() {
return asyncFun(i).then(function(res) {
console.log(res);
}).catch(function(ex) {
throw ex;
});
}).catch(function(ex) { throw ex });
})(i);
};
return chain
}

当我调用getData();时,它会在抛出错误后停止循环i = 4但我想继续所有 10 个条目的for循环。

任何帮助将不胜感激。

正如我在评论中所说,错误可能会被视为特殊值,因此您可以在链承诺后执行特殊行为。

试试这个代码:

function getData() {
var chain = $q.when();
for (var i = 0; i < 10; i++) {
(function(i) {
chain = chain.then(function() {
return asyncFun(i).then(function(res) {
console.log(res)
}).catch(function(ex) {
console.log(ex); // do not throw error but handle the error
});
}).catch(function(ex) { throw ex });
})(i);
};
return chain
}

最新更新