1

How to know when all of these requests are finished?

$.each(data.response.docs, function(i, item) {
    $.getJSON("jsp/informations.jsp?id=" + item.id, {}, function(data) {..});
});
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
earpolicy
  • 11
  • 1

1 Answers1

4

You could maintain a counter when each request completes, but that's a bit ugly and inelegant. Instead you could put the deferred objects returned from $.getJSON in to an array using map(). You can then apply than array to $.when. Something like this:

var requests = $.map(data.response.docs, function(i, item) {
    return $.getJSON('jsp/informations.jsp', { id: item.id }, function(data) {
        // ...
    });
}).get();

$.when.apply(requests).done(function() {
    // all requests complete...
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • nice! why not listen for `.always` so to also know when they fail? – kuzyn Feb 19 '16 at 16:11
  • 1
    `always` doesn't let you know if any of the requests failed, it just occurs after the requests complete regardless of result. If you want to know of any failures, you would use `.fail()`. – Rory McCrossan Feb 19 '16 at 16:16
  • Can you provide me the ugly and inelegant version please. I have not the time to change all the code inside function(data) {} Thanks ! – earpolicy Feb 19 '16 at 16:49
  • @earpolicy The method above means you don't have to change the code in that function. Its the counter method which means that you would have to (hence why it's ugly) – Rory McCrossan Feb 19 '16 at 16:50
  • There's no reason that wouldn't work, assuming the underlying object is valid. – Rory McCrossan Feb 19 '16 at 17:06