jQuery: What is the difference between deferred.always() and deferred.then()?

跟風遠走 提交于 2019-12-18 11:48:16

问题


Seems to me that both does the same thing.

Docs:

  • deferred.always()

  • deferred.then()


回答1:


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




回答2:


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();
});



回答3:


Prior to jQuery 1.8: .always(fn) is equivalent to .then(fn, fn)

As of jQuery 1.8: .always(fn) is similar to .then(fn, fn) but it differs in what is returned (see http://api.jquery.com/deferred.then/ for details)




回答4:


The big benefit of then (as of 1.8) is the capability to chain tasks explicitly because it returns a promise which will be resolved with the result of the callback(s)

Example from documentation:

var request = $.ajax( url, { dataType: "json" } ),
    chained = request.then(function( data ) {
      return $.ajax( url2, { data: { user: data.userId } } );
    });

chained.done(function( data ) {
  // data retrieved from url2 as provided by the first request
});


来源:https://stackoverflow.com/questions/12448171/jquery-what-is-the-difference-between-deferred-always-and-deferred-then

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!