Don't ever use $.get
or $.post
. Instead use $.ajax
and provide both a success
-handler and an error
-handler.
A deferred objects has two properties, it is a state object, and it takes care of callback management.
Upon creation of Deferred the state is 'pending'
var def = $.Deferred();
When the call resolve is made, the state transitions to 'resolved'
def.resolve();
The state can be inspected with:
def.state(); // "resolved"
After a transition happened, the object has finished and remains in this state. Even if you would reject()
it afterwards.
To make practical use of the object, we can define callbacks such as 'done', 'fail' and 'always' which function on either resolving or rejecting the deferred. Always will, as the name implies, always happen. this is comparable to a finally in a try-catch.
var def = $.Deferred();
def.done(function() {
console.log("Resolved");
});
def.fail(function() {
console.log("Rejected");
});
def.always(function() {
console.log("Finally");
});
def.reject();
//def.state();
Async functions!
deferred.when()
deals with subordinates
deferred.then()
passes result on to interested functions.
when object has been resolved already, they will execute immediately
Note: state can be read as boolean values using the following methods:
def.isRejected(); // false
def.isResolved(); // true
However, these functions are deprecated since 1.7 and also cause to not trigger then() which is attached after performing either of these calls. I suggest to not use them!