jQuery
documentation on jQuery.post( )
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
What is the difference between the success:
parameter and the jqXHR.done( )
method; if there is none, what is the entire point of the jqXHR.done( )
method?
The reason to prefer Promises over callback functions is to have multiple callbacks and to avoid the problems like Callback Hell.
Callback hell (for more details, refer http://callbackhell.com/): Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:
With Promises above code can be rewritten as below:
jQuery used to ONLY have the callback functions for
success
anderror
andcomplete
.Then, they decided to support promises with the jqXHR object and that's when they added
.done()
,.fail()
,.always()
, etc... in the spirit of the promise API. These new methods serve much the same purpose as the callbacks but in a different form. You can use whichever API style works better for your coding style.As people get more and more familiar with promises and as more and more async operations use that concept, I suspect that more and more people will move to the promise API over time, but in the meantime jQuery supports both.
The
.success()
method has been deprecated in favor of the common promise object method names.From the jQuery doc, you can see how various promise methods relate to the callback types:
If you want to code in a way that is more compliant with the ES6 Promises standard, then of these four options you would only use
.then()
.Both
.done()
and.success()
are callback functions and they essentially function the same way.Here's the documentation. The difference is that
.success()
is deprecated as of jQuery 1.8. You should use.done()
instead.In case you don't want to click the link:
From the doc:
The point it is just an alternative for success callback option, and
jqXHR.success()
is deprecated.