Seems to me that both does the same thing.
Docs:
deferred.always()
deferred.then()
The Deferred object, introduced in jQuery 1.5, is a chainable utility object created by calling the jQuery. Deferred() method. It can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
A promise represents a value that is not yet known. This can better be understood as a proxy for a value not necessarily known when the promise is created. A deferred represents work that is not yet finished. A deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.
A deferred object is an object that can create a promise and change its state to resolved or rejected . Deferreds are typically used if you write your own function and want to provide a promise to the calling code. You are the producer of the value. A promise is, as the name says, a promise about future value.
The defer attribute is a boolean attribute. If the defer attribute is set, it specifies that the script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.
It would seem that deferred.then()
allows you to pass two separate callbacks for success and failure, whereas deferred.always()
takes n
number of callbacks which will all be called regardless of the outcome of the initial event.
I would say use deferred.always()
in the cases where success/failure of the initial event are not important
With .then()
you can provide an individual callback for when the $.Deferred
is resolved (done
), and another for when the $.Deferred
is rejected (fail
).
.always()
, on the other hand, allows you to provide a callback that always gets executed, whether the $.Deferred
has been resolved or rejected. In other words, within this callback, it doesn't matter if the AJAX call has failed or has been been successfully executed.
I tend to put code in .always()
when I want that code to run everytime, and independently of whether the $.Deferred
was resolved successfully or not. For example, to clear an AJAX loading indicator or to hide a progress bar. Using .then()
you'd have something like this:
$.get("/some/url").then(function () { // done callback $(".progress-bar").hide(); }, function () { // fail callback $(".progress-bar").hide(); });
Whilst if you used .always()
, you'd just need a single callback, because you always want to hide the progress bar, no matter if the $.Deferred
was resolved or rejected:
$.get("/some/url").always(function () { $(".progress-bar").hide(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With