2017-06-19 53 views
0

我在處理多個jquery ajax調用時遇到了一些問題,有超時錯誤,但我怎麼知道這是哪個請求錯誤?如何使用Deferred處理多個ajax請求錯誤?

$.when(ajaxDeferred1, ajaxDeferred2) 
    .done(function(result1, result2) {}) 
    .fail(function(response, statusText) { 
    // how do I know which(ajaxDeferred1 or ajaxDeferred2) ajax call error this is? 
}); 

ajaxDeferred1

$.ajax({ 
    method: 'GET', 
    url: xxx, 
    timeout: 5000, 
}); 

我知道我可以通過把 '.fail()' 對每個請求處理錯誤,但有什麼辦法處理錯誤上面的方法?

走得更遠,我能像這樣處理嗎?

$.when(ajaxDeferred1, ajaxDeferred2) 
    .done(function(result1, result2) {}) 
    .fail(function(errorForRequest1, errorForRequest2) { 
    // handle error 
}); 

編輯:

我想我需要讓我的問題更加清晰。在上面的例子:

$.when(ajaxDeferred1, ajaxDeferred2) 
    .done(function(result1, result2) {}) 
    .fail(function(errorForRequest1, errorForRequest2) { 
    // if all request has done, but one or more request has got error, return the error here then! 
    // So I can handle which part UI should show and which UI part I should hide due to the error! 
}); 

我希望得到「完成」結果,當一切都沒有錯誤做,當所有被但一個或多個請求得到「錯誤」遇到的問題,並返回他們都一起變成'.fail()'。

回答

1

我喜歡@Miguel莫塔的答案。但是作爲替代方案,如果它失敗,你會得到你的延期對象。所以你可以添加一些數據:

var dfd1 = jQuery.ajax({ 
    method: 'GET', 
    url: 'some request that fails first', 
    timeout: 1 
}); 

dfd1.id = 1; 

var dfd2 = jQuery.ajax({ 
    method: 'GET', 
    url: 'some request that fails second', 
    timeout: 1000 
}); 

dfd2.id = 2; 

jQuery.when(dfd1, dfd2) 
    .done(function() { }) 
    .fail(function (request) { 
     // id: 1 
     console.log('id: ' + request.id); 
    }); 
+0

嗨,這更接近我的內涵。唯一的問題是'失敗()'將阻止其他Ajax請求繼續,我編輯了我的問題。 – Kim

1

您可以使用.always()並在其內迭代每個承諾並檢查其是否已解決或失敗。

var promises = [ajaxDeferred1, ajaxDeferred2] 

$.when.apply($, promises) 
    .always(function() { 
    $.each(promises, function(i) { 
     this.done(function(result) { 
     console.log('promise', i, 'resolved'); 
     }).fail(function(error) { 
     console.log('promise', i, 'failed'); 
     }); 
    }); 
    }); 

的jsfiddle演示:https://jsfiddle.net/pr45eov1/3/