Phillip Senn
Phillip Senn

Reputation: 47663

jQuery Deferred vs jqXHR

I use:

var jqXHR = $.ajax(settings);
jqXHR.success(function(result){});
jqXHR.error(function(result){});
jqXHR.complete(function(result){});

But version 1.5 has added the deferred object.

Q: In general, when do you use success, error and complete methods vs. the new hotness of deferred then, done and fail?

Upvotes: 17

Views: 6036

Answers (2)

Alnitak
Alnitak

Reputation: 340055

For $.ajax() and family .success is merely a synonym for Deferred's .done, and likewise .error is a synonym for .fail.

So in fact the examples you show are already deferred methods, but with different names.

.complete is mostly a synonym for the new jQuery 1.6 .always, and you can get the same effect using $.then(cb, cb), which will cause cb to be invoked whether the AJAX call succeeds or not. I believe there are minor differences in which parameters are passed to the "fail" callbacks between the .complete, .always and $.then variants.

I personally prefer to use the Deferred version of those named functions, because then you don't need to worry about whether your deferred objects are jqXHRs or not. Only jqXHRs have .success, .error, and .complete, but every Deferred (including jqXHRs) has .done, .fail and .always.

EDIT it seems the jQuery devs agree with me - they've announced that .success, .error and .complete will be deprecated in jQuery 1.8

Upvotes: 17

gradbot
gradbot

Reputation: 13862

Deferred is meant to replace jqXHR and abstracts the idea of success and error beyond ajax.

A quick look at the source code: jQuery 1.6.1

// completeDeferred is resolved in only one place.
completeDeferred.resolveWith( callbackContext, [ jqXHR, statusText ] );

deferred.promise( jqXHR ); // this attaches the promise methods to jqXHR
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.done;

I made a cheese slide show for work about how deferred is useful.

Upvotes: 9

Related Questions