views:

56

answers:

1

I have a chain of async calls, linked together using dojo.Deferred objects as async wrapper (at least how i understand it) and the .then() function to 'link' the async calls.

At any one of the links in the chain, some test could fail (such as my async store fetch returned no objects, etc) and i want to gracefully exit the entire .then() chain.

This is the form of the chain im using. How do i kill the entire chain where i indicate?

asyncFunc(...).then( function(args) {
    //stuff...
    return myDeferredReturningFunction(args);
}).then( function(args2) {
    //do some test on args2
    //if test fails, **how to cancel the chain here?**
}).then( function(args3) { ... etc etc ...

Note: Maybe someone can tag this as 'dojo.Deferred'?

+1  A: 

Throwing an exception should be one easy way to bail out, since it'll jump out of any callbacks and into any complementary or subsequent errbacks.

Quick example:

dojo.xhrGet({url:'base.php'})
    .then(function() { console.log('foo'); throw 'argh!';})
    .then(function() { console.log('bar'); }); // bar never gets printed

More info:

http://www.sitepen.com/blog/2009/03/31/queued-demystifying-deferreds/

http://www.sitepen.com/blog/2010/05/03/robust-promises-with-dojo-deferred-1-5/

Ken