0

I am calling jquery async calls in for loop like that:

for (var index = 0; index < activeSheets.length; index++) {
          service.getAsync().then(donecallback, failcallback);
}

and when I get donecallback, based on data returned i need to run another for loop and run even more calls,

is there any nice simple way to wait till all of them are finished and see if all passed or some failed ?

kosnkov
  • 5,609
  • 13
  • 66
  • 107

2 Answers2

2

Use the jQuery deferred API. https://api.jquery.com/jquery.when/

It expects multiple promises as arguments.

$.when(promise, promise, promise)
  .done(function success() { })
  .fail(function failure() { })
  .always(function always() { });

It then resolves if all of the promises succeed, or fails if any of them fail.

Dan Prince
  • 29,491
  • 13
  • 89
  • 120
  • 1
    You cannot pass this way array of promises to jq `$.when()` method, it should be e.g: `$.when.apply($, [promise, promise, promise])` – A. Wolff Nov 03 '15 at 14:22
0

You're probably looking for Promise.all(), it will execute all the promises and wait until they all pass or one of them fails.

var asyncs = [];
for (var index = 0; index < activeSheets.length; index++) {
    asyncs.push(service.getAsync());
}
Promise.all(asyncs).then(donecallback, failcallback);
TbWill4321
  • 8,626
  • 3
  • 27
  • 25