![](/img/trans.png)
[英]ajax: how to identify which api request has failed inside the then after all requests have completed
[英]how can we identify which ajax failed with multiple ajax requests once all the requests are completed?
我有兩個ajax電話,即
var ajax1 = $.ajax({ url: Url1 });
var ajax2 = $.ajax({ url: Url2 });
$.when(ajax1, ajax2).then(function (response1, response2) {
});
我們希望有條件地處理這些API延遲請求的失敗情況:
WinAjax1_WinAjax2();
WinAjax1_LoseAjax2();
LoseAjax1_WinAjax2();
LoseAjax1_LoseAjax2();
如果我在各自的ajax的.fail
中放入邏輯,我將不知道其他ajax的響應。 如果我把.fail
中.when
的失敗,我不能夠確定它是失敗的。
一旦所有請求都完成后,有人可以幫助我如何確定哪個ajax因多個ajax請求而失敗?
jQuery延遲對象具有狀態方法 。 因此,您可以使用$.when
,如果失敗,請檢查每個延遲對象的狀態。
var d1 = jQuery.Deferred(); var d2 = jQuery.Deferred(); $.when(d1, d2).then(function(v1, v2) { // do something on succes }).fail(function() { console.log(d1.state()); // resolved console.log(d2.state()); // rejected }); d1.resolve( "Fish" ); d2.reject( "Pizza fail" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
編輯:看來我錯過了您的主要目標。 如果您需要等待直到所有請求都完成(已解決或被拒絕)。 然后$.when
將無濟於事,因為一旦拒絕任何請求而不等待其他請求,它將被拒絕。
在這種情況下,我建議您數完所有請求。 然后檢查其狀態。
var d1 = jQuery.Deferred(); var d2 = jQuery.Deferred(); var activeRequests = 2; function onComplete() { activeRequests--; if (!activeRequests) { // check deferred object states here console.log(d1.state()); console.log(d2.state()); } } d1.always(onComplete); d2.always(onComplete); d2.reject( "Pizza fail" ); d1.resolve( "Fish" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案與此處提到的解決方案完全相同。
var d1 = $.Deferred();
var d2 = $.Deferred();
var j1 = $.getJSON(...).complete(d1.resolve);
var j2 = $.getJSON(...).complete(d2.resolve);
$.when(d1,d2).done(function() {
// will fire when j1 AND j2 are both resolved OR rejected
// check j1.isResolved() and j2.isResolved() to find which failed
});
您可以在任一ajax調用之后顯式調用一個函數,以檢查所有ajax調用是否成功。 例如:
var ajax1_success = false,
ajax1_called = false,
ajax2_success = false,
ajax2_called = false;
var afterAjax = function () {
if (!(ajax1_called && ajax2_called)) {
return;
}
// add conditionals here
};
var ajax1 = $.ajax({ url: Url1 })
.success(function() {
ajax1_success = true;
}).always(function() {
ajax1_called = true;
afterAjax();
});
var ajax2 = $.ajax({ url: Url2 })
.success(function() {
ajax2_success = true;
}).always(function() {
ajax2_called = true;
afterAjax();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.