链接上的条件在jquery中延迟

Joe*_*ito 3 javascript ajax jquery chaining deferred

$.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!");
});
Run Code Online (Sandbox Code Playgroud)

我做得对吗?如果条件返回false,如何阻止下一个链执行,以及如何执行此操作:

if(data){
   console.log('Success');
}
Run Code Online (Sandbox Code Playgroud)

这些代码可以介于这些代码之间.then吗?

Bee*_*oot 5

乔伊,无论你是否做得对,取决于你想要达到的细节.

如果您正在尝试.then()使用终端构建一个长链,那么.done()每个.then()''done'处理程序要么:

  • 调用异步进程,或
  • 透明地将数据传递到.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");
});    
Run Code Online (Sandbox Code Playgroud)

但是,如果你试图做同样的事情,但每个.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(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");
});
Run Code Online (Sandbox Code Playgroud)