jQuery always vs. done vs. fail vs. then

July 24, 2015

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!

  1. Always – called when the deferred object resolved or rejected
  2. Done – called when the deferred object is resolved
  3. Fail – called when the deferred object is rejected
  4. 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');
});

Done

$.get( "www.yoursite.com/api" ).done(function() {
  console.log('this will run if the $.get succeeds');
});

Fail

$.get( "www.yoursite.com/api" ).fail(function() {
  console.log('this will run if the $.get fails');
});

Then

$.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.