乔伊,你做对与否取决于你想要达到的目标的细节。
如果您尝试.then()
使用终端构建一个长链.done()
,其中每个.then()
“完成”处理程序:
- 调用异步进程,或
- 透明地将数据传递到
.then()
链中的下一个
那么,代码应采用以下形式:
var promise = ...;//An expression that returns a resolved or resolvable promise, to get the chain started.
$.each(data, function(k, v) {
promise = promise.then(function() {//The `.then()` chain is built by assignment
if(data...) { return $.post(...); }
else { return data; }//Transparent pass-through of `data`
}).then(function(data) {
if(data...) { return $.post(...); }
else { return data; }//Transparent pass-through of `data`
});
});
promise.done(function() {
console.log("All Done!");
}).fail(function(jqXHR) {
console.log("Incomplete - an ajax call failed");
});
但是,如果您尝试做同样的事情,但每个.then()
“完成”处理程序的位置:
那么,代码应采用以下形式:
var promise = ...;//An expression that returns a resolved or resolvable promise, to get the chain started.
$.each(data, function(k, v) {
promise = promise.then(function(data) {
if(data...) { return $.post(...); }
else { return $.Deferred().reject(data).promise(); }//Force the chain to be interrupted
}).then(function(data) {
if(data...) { return $.post(...); }
else { return $.Deferred().reject(data).promise(); }//Force the chain to be interrupted
});
});
promise.done(function() {
console.log("All Done!");
}).fail(function(obj) {//Note: `obj` may be a data object or an jqXHR object depending on what caused rejection.
console.log("Incomplete - an ajax call failed or returned data determined that the then() chain should be interrupted");
});