假设我把$.Deferred
像这样。
$.each(data, function(k, v) {
promise.then(function() {
return $.post(...);
}).then(function(data) {
if(data)... // here is the conditions
return $.post(...);
}).then(function(data) {
if(data)... // here is another condition
return $.post(...);
})
});
promise.done(function() {
console.log("All Done!");
});
我做对了吗?如果条件返回 false,如何阻止下一个链执行,以及在哪里执行此操作:
if(data){
console.log('Success');
}
该代码可以在这些代码之间吗.then
s?
乔伊,你做得是否正确取决于你想要实现的目标的细节。
如果你想建造一个长的.then()
带终端的链.done()
,其中每个.then()
的“完成”处理程序:
- 调用异步进程,或者
- 透明地将数据传递给下一个
.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()
的“完成”处理程序:
- 调用异步进程,或者
- 打断
.then()
chain
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");
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)