Warning: Please consider that this post is over 9 years old and the content may no longer be relevant.
For those familiar with JavaScript Promises, jQuery’s Deferred.fail() handling can act unexpectedly. Standard Promises implementations allow the first catch handler to deal with the error and then return to normal execution flow (see JavaScript Promises: There and back again). jQuery on the other hand appears to execute all fail handlers, in the order they were defined with no chance to recover normal flow.
For an example, consider this code using Chrome’s built in Promises support:
The output of which would be:
And a similar jQuery implementation:
The output of which would be:
Note how Chrome’s Promises recovered after the first catch handler was executed and called the ‘recovered’ function. jQuery does not. Another small difference is that Promise.reject() and Promise.resolve() may only return a single object, whereas jQuery passes all parameters to it’s reject or resolve functions onto the then or fail handlers.
This becomes an issue in jQuery if you are trying to map different errors into a single error handler. For instance, if you’re chaining a jqXHR object from an $.ajax() call, you may want want to map jQuery’s error parameters (jqXHR, textStatus, errorThrown) to match a single error handler that just accepts an error message. Using Standard Promises this could be achieved by chaining a catch handler after the ajax request that returns a new rejected promise with the correct parameter. E.g.
But to do the same thing in jQuery, you need to wrap the ajax call and fail handler (mapper) in a new Deferred object, e.g.