【发布时间】:2016-06-07 13:15:55
【问题描述】:
在jQuery的aJax方法中,传入的对象包括成功和错误处理。如果已经可以在 ajax 请求参数中进行处理,为什么还需要使用 #then 或 #done 或 #fail 之类的方法?
【问题讨论】:
-
它在功能上是等效的,但是 then/done/fail 允许您将请求的代码和接收响应的代码分开。 stackoverflow.com/questions/13168572/…
在jQuery的aJax方法中,传入的对象包括成功和错误处理。如果已经可以在 ajax 请求参数中进行处理,为什么还需要使用 #then 或 #done 或 #fail 之类的方法?
【问题讨论】:
success 和 error 不能用于传递由 $.ajax 返回的承诺链中的承诺
您不能像在then() 中那样对这些方法进行任何return。
考虑一系列 ajax 请求,这些请求必须全部完成,其他代码才能执行。
$.getJSON(url)
.then(function(resp1) {
// this request won't run until previous one completed
return $.getJSON(resp1.urlValue).done(function(resp2) {
// can do things in individual request done also
});
}).then(function(resp2) {
return $.getJSON(resp2.urlValue, function(resp3){
// or do something in success callback for this request
});
}).then(function() {
// do something here now that all the requests have resolved
}).fail(function() {
alert('I fire if any of the above fail');
});
此链无法使用成功回调来工作
【讨论】: