Assuming createIdentityDetails() and sendIdentityDetails() are promising asynchronous functions ...
If what we see in the question is a whole chain of promises, then processing the error condition is simple. There is no need to convert success into failure or failure in success, or from one type of promise to another.
$.ajax(url).then(function() { cleanup(); }, function(err) { createIdentityDetails() .then(sendIdentityDetails); });
This will work regardless of the type of promise returned by createIdentityDetails() jQuery or non-jQuery.
If, however, there is more, for example, the caller function should be informed about the results, then you need to do more, and it depends on how you want to report the possible results.
Report id already exists as failure and "new id created as successful
Here is what the question suggests
function foo() { return $.ajax(url).then(function() { cleanup(); return $.Deferred().reject('failure: ID already exists'); }, function(err) { return createIdentityDetails() .then(sendIdentityDetails) .then(function() { return $.when('success: new ID created'); }); }); }
Report both types of results as success
This seems more reasonable as the error processed will be reported as successful. Only unpredictable unhandled errors will be reported as such.
function foo() { return $.ajax(url).then(function() { cleanup(); return 'success: ID already exists'; }, function(err) { return createIdentityDetails() .then(sendIdentityDetails) .then(function() { return $.when('success: new ID created'); }); }); }
Whatever reporting strategy is adopted, it is very important which type of promise createIdentityDetails() returns. As the first promise in a chain, he defines the behavior of both of his chains.
- If
createIdentityDetails() returns its own ES6 promise, then no worries, most tastes of the promise, even jQuery, will be learned. - if
createIdentityDetails() returns a jQuery promise, then only jQuery promises will be acquired. Therefore, sendIdentityDetails() should also return a jQuery promise (or an ES6 promise that should be processed into jQuery with $.Deferred(...) ), as well as the final success converter (as mentioned above).
You can see the mix effects of jQuery and ES6 promises in these two ways here . The first warning is generated by the second block of code, and this is not what is expected. The second warning is generated by the first block and correctly gives the result 98 + 1 + 1 = 100.