2015-04-23 46 views
1

下面是我帶有promise的多個ajax調用。在jquery中獲取多個延遲對象的響應

$(window).load(function(){ 
$.when(getApiModemList()).done(function(vendors){ 

    var deferreds = calculateApiBalances(vendors); 

    $.when.apply($,deferreds).done(function(balance) { 
    console.log(balance); 
    console.log("All Done"); 
    }); 

}); 


function getApiModemList(){ 
    return $.getJSON("url"); 
} 

function calculateApiBalances(vendors) 
    { 
    var defer=[]; 
    $.each(vendors,function(k,v){ 
    defer.push($.getJSON(someurl)); 
    }); 
    return defer; 
} 

}); 

函數calculateApiBalances()返回我一些餘額,我需要總結得到所有餘額的總和。 但是,當打印console.log(餘額)它不提供我有效的數組平衡JSON。 另一個問題是如果calculateApiBalances()中的任何一個ajax調用失敗,它將不打印All Done。 上面的代碼應該做些什麼來實現這一點。

+2

首先,[避免延遲反模式](http://stackoverflow.com/q/23803743/1048572)! – Bergi

+0

數組包含哪些錯誤?通常,加入的承諾會被拒絕。 – Bergi

+0

@Bergi。修正了anitpattern問題。我不在乎,如果一些Ajax調用失敗我只需要考慮成功的Ajax調用的平衡。是否有可能? – Vibhas

回答

1

但是,當打印console.log(餘額)它沒有提供我有效的數組平衡json。

這是一個奇怪的事$.when。它不提供數組,但用多個參數調用您的回調。

另一個問題是,如果在calculateApiBalances()中的任何一個ajax調用失敗,它不打印所有完成。

是的,因爲當一個承諾失敗時,整個$.when()承諾立即被拒絕,並且您沒有任何錯誤處理程序。如果您想要始終獲取數組(可能無效的響應),則必須單獨捕獲錯誤。另見$.Deferred: How to detect when every promise has been executed

在上面的代碼中應該做些什麼來實現這一點。

首先,avoid the deferred antipattern :-)

$(window).load(function() { 
    getApiModemList().then(calculateApiBalances).then(function() { 
     var balance = Array.prototype.slice.call(arguments); 
     console.log(balance); 
     console.log("All Done"); 
    }); 
}); 


function getApiModemList() { 
    return $.getJSON(somurl).then(function(res) { 
     return res.data; 
    }); 
} 

function calculateApiBalances(vendors) { 
    return $.when.apply($, $.map(vendors, function(v, k) { 
     return $.getJSON(someurl).then(null, $.when); 
    })); 
} 

編輯的流浪者:

而且這裏有一個版本的主程序的與餘額相加的機制。

getApiModemList().then(calculateApiBalances).then(function() { 
     var sumOfBalances = Array.prototype.reduce.call(arguments, function(tot, obj) { 
      return tot + (+obj.balance || 0); 
     }, 0); 
     console.log(sumOfBalances); 
     console.log("All Done"); 
    }); 

obj$.getJSON(someurl)calculateApiBalances()承諾的對象。在出現$.getJSON()錯誤的情況下,obj將爲jqXHR對象,obj.balance將爲undefined+obj.balance將爲NaN,因此默認爲加零;否則加上obj.balance

如果你想知道有多少getJSON請求成功,有多少不成功,那麼還有一些代碼要寫,但不是很多。

+0

@Roamer:啊,我錯過了這個要求,謝謝編輯它。然而,你的編輯是在合法性的邊緣,我怎麼能對它進行調整呢? :-) – Bergi

+0

Bergi,「合法性的邊緣」? –

+0

對不起,這裏是非本族人的奇怪術語。我的意思是編輯是邊緣的,可能不會被接受爲編輯建議(「太劇烈的變化」,「嘗試回覆」)。雖然我很好,謝謝。 – Bergi