【发布时间】:2015-04-23 07:08:37
【问题描述】:
以下是我的多个带有承诺的 ajax 调用。
$(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(balance) 时,它没有为我提供有效的 balance json 数组。 另一个问题是,如果我在 calculateApiBalances() 中的任何一个 ajax 调用失败,它不会打印 All Done。 在上面的代码中应该做些什么来实现这一点。
【问题讨论】:
-
如果出现错误,数组应该包含什么?通常,加入的 Promise 会被简单地拒绝。
-
@Bergi 。修复了 anitpattern 问题。我不在乎某些 ajax 调用是否失败我只需要考虑成功 ajax 调用的平衡。有可能吗?
标签: javascript jquery ajax promise jquery-deferred