Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use .promise().done() on $.each json array when done/completed?

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?
like image 690
paocom Avatar asked Jun 30 '14 07:06

paocom


People also ask

How do you resolve an array of promises?

all() The Promise. all() method takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises. This returned promise will fulfill when all of the input's promises have fulfilled, or if the input iterable contains no promises.

How do you wait for promises to complete?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.


1 Answers

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
});
like image 67
jfriend00 Avatar answered Sep 19 '22 15:09

jfriend00