Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping an AngularJS promise chain

I'm trying to figure out a good way to say "Do all of these things, but bail in the case that any of them fails"

What I have right now:

var defer = $q.defer();

this
    .load( thingy ) // returns a promise

    .then( this.doSomethingA.bind( this ) )
    .then( this.doSomethingB.bind( this ) )
    .then( this.doSomethingC.bind( this ) )
    .then( this.doSomethingD.bind( this ) )

    .then( function(){
        defer.resolve( this );
    } );
    ;

return defer.promise;

What I ultimately want is to somehow catch any error on that chain so I can pass it on to the defer promise above. I don't particularly care if the syntax is kept similar to what I have above.

Or even if anyone can just tell me how to stop the above chain.

like image 884
Nobody Avatar asked May 30 '13 23:05

Nobody


1 Answers

You can stop angularjs chain by returning rejected promise inside any then callback.

load()
.then(doA)
.then(doB)
.then(doC)
.then(doD);

where doA, doB, doC, doD can have logic like this:

var doA = function() {
    if(shouldFail) {
        return $q.reject();
    }
}
like image 175
Max Podriezov Avatar answered Sep 28 '22 08:09

Max Podriezov