Branch Processing with Promises

I have a problem with jQuery 1.9.1 promises, where I potentially need conditional logic that will return another deferred version, and I'm not sure how to handle it. This was my best attempt, but as you can see from the comments, when I got to the else branch, I hit the second .then () function anyway, where I hope I can return to the user. Any patterns to handle such a scenario?

storage.provision(c) .then(function(rc){ if(rc === 0){ storage.write(c); }else{ return options.onSuccess(rc); //how i got back to the users callbacks/promise, but this //takes me to the .then below } }) //storage.write returns a promise as well, do I do another .then // like this? .then(function(rc){ //I was hoping this would catch, the storage.write() case, and it does, but it also catches //the retun options.onSuccess(rc) in the else case. options.onSuccess(rc); }) .fail(function(e){ //handle error using .reject() }); 
+6
source share
1 answer

This becomes easier if you accept that options.onSuccess(rc); executed unconditionally in the second .then() , but never in the first.

So the first .then() should go through rc :

  • if rc === 0 , in response to storage.write(c) completion
  • or immediately if rc !== 0 .

.then() really convenient for this, because it naturally allows you to return the value of a new promise from its done callback.

 storage.provision(c).then(function(rc) { if(rc === 0) { var dfrd = $.Deferred(); storage.write(c).done(function() { dfrd.resolve(rc); }).fail(dfrd.fail); return dfrd.promise(); } else { return rc;//pass on rc to the second .then() } }).then(function(rc){ options.onSuccess(rc); }).fail(function(e){ //handle error using .reject() }); 

I am sure that there are other approaches, but this is the closest that I can come up with for your original concept.

It would be nice to create a new Deferred when rc === 0 , but this is the most realistic approach to passing to rc , avoiding the need to modify storage.write() to behave this way.

+4
source

All Articles