How can I make a callback after all the AJAX requests in the loop?
I have a loop that iterates through an array of HTML elements. Each iteration makes a GET request (whose URL depends on the current item) and does some additional processing. If I wanted to report that all requests have been completed, how would I do it?
HTML elements are formatted
<td align="left">Item name</td>
Here's what I have:
var url = "http://example.com/page.phtml?item=";
var items = $(itemList).find('table tbody tr td[align=left]');
for (var i = 0; i < items.length; i++) {
(function (i) {
var itemName = items[i].innerHTML;
$.get(url + itemName, function(data) {
// process some stuff
console.log("Processing item " + itemName);
});
})(i);
}
As you can see, the function that makes the GET call is in a closure. After all requests are complete, how can I use a callback, for example console.log("DONE")
?
source to share
You can use jQuery $.when()
:
var url = "http://example.com/page.phtml?item=";
var items = $(itemList).find('table tbody tr td[align=left]');
var promises = items.map(function(i, elem) {
var itemName = items[i].innerHTML;
return $.get(url + itemName, function(data) {
// process some stuff
console.log("Processing item " + itemName);
});
}).get();
$.when.apply($, promises).done(function() {
// all promises done here
});
You accumulate an array of promises (that's what is returned from $.get()
) and then pass that array from promises to $.when()
and it creates a cumulative promise that is resolved when all other promises are resolved.
source to share
You have two options. The simple method is to count the number in the callback handler and then only the following code is executed after the number of js callbacks is equal to the number of your elements in the array.
More expensive but valuable is using promises. There are many libraries for using promises. If you decide to go this route, I suggest looking for a .all or .when function that can handle an array of promises.
source to share