-1

I have a function which gives me response in sequence for asynchronous call using promises for a for loop but loop breaks when i got a exception from code, but i want to continue my loop even after a exception throw from function.

my async function is

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

and chain function is

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
}

and when i call getData(); it stop the loop after throw error on i = 4 but i want to continue the for loop for all 10 entry.

Any help will be appreciated.

Gaurav Kumar Singh
  • 1,550
  • 3
  • 11
  • 31

1 Answers1

0

As I said in comment, the errors may be treated as special values so you can perform special behaviours after the chain promises.

Try this code:

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
}
Wing-On Yuen
  • 657
  • 5
  • 9