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

后端 未结 4 1852
离开以前
离开以前 2020-12-29 04:03

Seems to me that both does the same thing.

Docs:

  • deferred.always()

  • deferred.then()

相关标签:
4条回答
  • 2020-12-29 04:28

    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();
    });
    
    0 讨论(0)
  • 2020-12-29 04:30

    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

    0 讨论(0)
  • 2020-12-29 04:36

    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
    });
    
    0 讨论(0)
  • 2020-12-29 04:39

    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)

    0 讨论(0)
提交回复
热议问题