简体   繁体   English

jQuery Deferred 的完成与成功回调

[英]jQuery Deferred's done vs success callback

Are there any technical differences between the following callback methods?以下回调方法之间是否存在技术差异?

1 1

$.ajax({
  ...
  success: function(data, textStatus, jqXHR) {
    foo(data);
  },
  error: function (jqXHR, textStatus, errorThrown ) {
    bar();
  }
});

2 2

$.ajax(...)
  .done(function(data) {
    foo(data);
  })
  .fail(function() {
    bar();
  });

3 3

$.ajax(...)
  .then(function(data) {
    foo(data);
  }, function() {
    bar();
  });

With little experience, I am not sure they are correct examples for passing data to foo() .由于经验不足,我不确定它们是否是将data传递给foo()正确示例。 (Please correct me if I am wrong.) (如果我错了,请纠正我。)

With done / fail , we can't track other data like jqXHR , textStatus , errorThrown , etc. Am I right?使用done / fail ,我们无法跟踪其他数据,如jqXHRtextStatuserrorThrown等。我说得对吗?

Is there a complete equivalence for the done / fail method? done / fail方法是否有complete等价的方法?

From your experience, is one better than/preferred over the others at certain situations?根据您的经验,在某些情况下,一个比其他的更好/更受欢迎吗?

If I use both success and done / then , will one run before the other definitely or it can't be certain which will run before the other definitely?如果我同时使用successdone / then ,一个肯定会在另一个之前运行还是不能确定哪个肯定会在另一个之前运行? Or is using success and done / then altogether not recommended?或者使用successdone / then完全不推荐?

One difference between jQuery .done() and .then() is the return value can be changed at .then() jQuery .done().then()区别之一是返回值可以在.then()处更改

See jQuery deferreds and promises - .then() vs .done()请参阅jQuery 延迟和承诺 - .then() 与 .done()

 $.Deferred(function(dfd) { dfd.resolve(1) }) .done(function(n) { return n + 1 }) .then(function(res) { console.log(res) // 1 })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>

 $.Deferred(function(dfd) { dfd.resolve(1) }) .then(function(n) { return n + 1 }) .then(function(res) { console.log(res) // 2 })
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM