链接上的条件在jquery中延迟

时间:2013-05-03 03:21:50

标签: javascript jquery ajax 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!");
});

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

if(data){
   console.log('Success');
}

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

2 个答案:

答案 0 :(得分:5)

乔伊,无论你是否正确行事取决于你想要达到的细节。

如果您尝试使用终端.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()'已完成'处理程序的位置:

  • 调用异步进程,或
  • 中断.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");
});

答案 1 :(得分:2)

jQuery's then返回一个新的承诺,由以下链式then监控。从先前的then返回的任何内容都将作为下一个then的第一个参数传递。

promise.then(function() {
  return $.post(...);
}).then(function(data) {
  //we return false or some indicator that next shouldn't run
  if(!data) return false; 
  //else we return something
  else return $.post(...);
}).then(function(data) {
  //here we receive false, we return early, preventing further code from executing
  if(!data) return false;
  //otherwise, the following code runs
  return $.post(...);
})