Nirs Nirs - 3 months ago 7
jQuery Question

Loop over a bunch of asynchronous operations and wait for them all to finish?

(Please don't mark as duplicate or at least point me to the correct answer as here I deal with multiple requests to form an array). I set up some url calls with the returned "data" values as an array. I plan to use this array to create the sum of all these values.

var data_num=[];
$.each(arr_urls, function( index, value ) {

$.getJSON(arr_urls[index], function (data) {
data_num.push(data);
});
});
alert(data_num);

Answer

You may already be familiar with why this doesn't work, and there are excellent explanations in an oft linked duplicate. However, this isn't entirely a duplicate. Because you're not asking this:

How do I return the response from an asynchronous operation?

You're asking something more like this:

How do I loop over a bunch of asynchronous operations and wait for them all to finish?

For that, you'd first need to put them into an array. Something like this:

var my_promises = [];
var data_num = [];
$.each(arr_urls, function( index, value ) {
  my_promises.push($.getJSON(arr_urls[index], function (data) {
      data_num.push(data);
  }));
}); 

This should give you an array called promises which holds references to the currently-executing asynchronous operations. Now you just need to wait for them all to complete. Something like this:

$.when.apply($, my_promises).then(function() {
    alert(data_num);
});

This should apply the .when() function to the entire array of promises, executing the callback only when that entire array has completed.

Comments