Haji
Haji

Reputation: 1775

jQuery Deferred .then() isn't called after .fail()

I'm using jQuery.Deferred and registering the done, fail and then handlers:

$.when( some_ajax(url) )
    .done(function(result){})
    .fail(function(){})
    .then(function(){}); //just like that, with a single parameter

I've found that when my ajax call succeeds, done and then callbacks are called, in this order. However when the ajax fails, the fail callback is called but I don't get to the then callback.

I've read the jQuery.Deferred documentation but couldn't find a hint regarding the reason for this behavior.

When using always instead of then, it is called in both cases - success and failure (first done/fail is called, then always is called). The documentation doesn't seem to indicate an expected difference between always and then in my described scenario, why do they behave differently?

Upvotes: 9

Views: 5644

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The syntax of .then() is .then(successCallback, failureCallbacl) that is why in case of success both are called and in case of failure only fail is called.

In your case you are passing only one callback to the .then() method, it will be registered as a success callback, so you have two success callbacks one registered with done() and another one with .then(). But for error case you have only one callback registered with .fail()

If you want a callback to be called irrespective of success/failure then use .always()

Upvotes: 21

Related Questions