jQuery’s
deferred objects
can be tough to get your head around. Specifically learning the difference between
always
,
done
,
fail
, and
then
. Let’s go over them really quick and then dive into some examples!
Always
– called when the deferred object resolved
or
rejected
Done
– called when the deferred object is resolved
Fail
– called when the deferred object is rejected
Then
– a nice shorthand that allows you to pass in a done and then optionally a fail and a progress
Some Examples
Let’s cement this with some easy examples!
Always
$.get( "www.yoursite.com/api" ).always(function() {
console.log('this will run whether the $.get fails or succeeds');
$.get( "www.yoursite.com/api" ).done(function() {
console.log('this will run if the $.get succeeds');
$.get( "www.yoursite.com/api" ).fail(function() {
console.log('this will run if the $.get fails');
$.get( "www.yoursite.com/api" ).then(
function() {
console.log('this will run if the $.get succeeds');
}, function() {
console.log('this will run if the $.get fails');
}, function() {
console.log('this will run if the deferred generates a progress update');
Hope that helps! There are a bunch of other cool methods you should check out! Let me know in the comments if you have any questions.
.then() doesn’t actually seem to be a shorthand for the others. It seems to function a little differently.
With .then(), you can return a new Deferred from your callbacks, and effectively chain your deferreds, whereas .done() doesn’t allow deferred chaining.
An example:
var a = $.Deferred();
var b = $.Deferred();
a.done(function() { console.log(“a1”); return b; }).done(function() { console.log(“a2”); });
b.done(function() {console.log(“b1”);});
a.resolve();
// Prints “a1” and “a2”
b.resolve();
// Prints “b1”
whereas:
var a = $.Deferred();
var b = $.Deferred();
a.then(function() { console.log(“a1”); return b; }).then(function() { console.log(“a2”); });
b.then(function() {console.log(“b1”);});
a.resolve();
// Prints “a1”
b.resolve();
// Prints “b1” and “a2”
The second .then() on the a is actually chained onto the return Deferred object from the first .then().
Privacy & Cookies: This site uses cookies. By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here:
Cookie Policy