jQuery deferred StackExchange API test
by hippietrail
HTML
<div id='console'></div>
JavaScript
function log(msg) {
var $out = $("<div />");
$out.html(msg);
$("#console").append($out);
}
function batch(a, b) {
var dfd = new jQuery.Deferred();
var arr = [];
arr.push(req(a));
arr.push(req(b));
log("....");
$.when.apply($, arr).then(function() {
log("----");
dfd.resolve();
});
return dfd.promise();
}
function req(cl_country) {
log(">> [" + cl_country + "]");
return $.getJSON("/echo/json/",
{ country: cl_country },
function(data) {
log("<< [" + cl_country + "]");
}
);
}
var arr = ["US", "CA", "MX", "AU", "KA"];
var chained = $.Deferred().resolve();
$.each(arr, function(unused_index, country) {
chained = chained.pipe(function() {
return batch(country, country + "2");
});
});