3

假设我$.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');
}

该代码可以在这些.thens 之间吗?

4

2 回答 2

6

乔伊,你做对与否取决于你想要达到的目标的细节。

如果您尝试.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");
});
于 2013-05-03T20:43:06.807 回答
2

jQuerythen返回一个新的 Promise,由下面的链式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(...);
})
于 2013-05-03T03:35:27.963 回答