19

I want to perform some action when $.each is done.

$.each(someArray, function(index, val) {

    //---------some async ajax action here per loop ---------
    $.ajax({...}).done(function(data){...});

}.promise().done(function(){...}); //<-------error here can't use with $.each
  • Not every jQuery function has a promise()?
  • How do I know when $.each array is done?
  • Can I change someArray to $someArray to use it?
stealthyninja
  • 10,343
  • 11
  • 51
  • 59
paocom
  • 235
  • 1
  • 3
  • 8

1 Answers1

40

As you've figured out, $.each() doesn't have a .promise() so you can't do it the way you were trying to. Instead, you can use $.when() to track when a bunch of promises returned by a group of Ajax functions have all been resolved:

var promises = [];
$.each(someArray, function(index, val) {
    //---------some async ajax action here per loop ---------
    promises.push($.ajax({...}).then(function(data){...}));
});
$.when.apply($, promises).then(function() {
    // code here when all ajax calls are done
    // you could also process all the results here if you want
    // rather than processing them individually
});

Or, rather than your $.each(), it's a bit cleaner to use .map():

$.when.apply($, someArray.map(function(item) {
    return $.ajax({...}).then(function(data){...});
})).then(function() {
    // all ajax calls done now
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • The .map didnt work for my situation (may be user error) but the promise array worked fantastically. Thanks!! (Sorry Necro but still helped) – Sicae Jan 25 '19 at 19:34
  • Thanks, but I don't know why so many answer on SO mark each().promise().done() as answer like this: https://stackoverflow.com/questions/2358205/invoking-a-jquery-function-after-each-has-completed – Cheung Oct 07 '21 at 04:04