javascript - Get response of multiple deferred objects in jquery -
below multiple ajax calls promises.
$(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; } });
function calculateapibalances() return me balance need sum total of balance . when print console.log(balance) doesnot provide me valid array of balance json. issue if 1 of ajax calls in calculateapibalances() fails doesnot prints done. should done in above code achieve this.
but when print console.log(balance) doesnot provide me valid array of balance json.
that's weird thing of $.when
. doesn't provide array, calls callback multiple arguments.
another issue if 1 of ajax calls in calculateapibalances() fails doesnot prints done.
yes, because when 1 promise fails whole $.when()
promise rejected immediately, , don't have error handler. you'll have catch errors individually if want array (of possibly invalid responses). see $.deferred: how detect when every promise has been executed.
what should done in above code achieve this.
first of all, avoid 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); })); }
edit roamer:
and here's version of master routine mechanism summing balances.
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
object promised $.getjson(someurl)
in calculateapibalances()
. in case of $.getjson()
error, obj
jqxhr object, obj.balance
undefined
, +obj.balance
nan
, therefore default adding zero; otherwise add obj.balance
.
if wanted know how many of getjson requests successful , how many unsuccessful, there's more code write, not lot.