I am polling data asynchronously, from a number of sources, in a round-robin approach and wish to repeat the poll when all of these polls have finished. I am trying to use the jQuery Deferred object together with "always" to repeat my polling as shown in the code below:
function makeAjaxCall(region) {
var params = {
'action': POLLER.action,
},
url = POLLER.region_to_url[region];
return $.ajax({
dataType: "json",
url: url,
data: params,
success: (function(region) {
return function(result, status) {
handleAjaxResult(result, status, region);
};
})(region),
error: (function(region) {
return function(jqXHR, textStatus, errorThrown) {
handleAjaxError(jqXHR, textStatus, errorThrown, region);
};
})(region)
});
}
function nextPoll() {
if(!polling) {
return;
}
var requests = [];
$.each(POLLER.regions, function(i, region) {
requests.push(makeAjaxCall(region));
});
$.when.apply($, requests)
.always(function() {
log("deferred.always ", this)
updateSummary();
var delay = POLLER.POLLER_INTERVAL_MS;
if (delay != 0) {
pollerTimeout = setTimeout(nextPoll, delay);
}
}).fail(function() {
log("fail for ",this)
});
}
My problem is that when one of my polls fails, the "always" block is called. I may be assuming incorrectly that "always" should be called after all requests have completed or failed. It is my intention to have it behave this way, so any tips on a different, perhaps simpler, approach would be great.