Reputation: 23921
I know how to use jquery ajax like this. In other words, I understand that .fail
gets called on failure etc.
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
I also understand that $.ajax("example.php")
returns an object representing a part of the DOM and that there are anonymous functions passed as parameters to done/fail/always. So far so good. I also get method chaining (or "cascading"): how a function call on an object returns the object, so you can just call the object again with the next method in the chain.
However, I am trying to understand how jquery "knows" which of the methods to call from the chain above. It's not like done returns and then fail (the next method in the chain) is called. So what's going on with this syntax? How does it work under the hood?
Upvotes: 1
Views: 1599
Reputation: 6130
Quote from the https://api.jquery.com/jQuery.ajax/
The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include: ...
Read more at https://api.jquery.com/category/deferred-object/
Upvotes: 2