2015-04-23 52 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