2013-05-03 44 views
3

讓我說我這樣鏈接$.Deferred這樣。在jquery推遲鏈條件

$.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秒之間?

回答

3

喬伊,不管你是否做得對,取決於你想要實現的細節。

如果正在試圖建立一個長.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"); 
}); 
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(...); 
}) 
+0

我能否在返回false之前記錄日誌? – 2013-05-03 03:38:01

+0

@JoeySalacHipolito'if(data)'位於哪裏? – Joseph 2013-05-03 04:04:12

+0

在所有條件下,例如,如果第一個,然後返回false,我想'的console.log()'鏈的每個狀態... – 2013-05-03 04:10:47