$.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
promise()
?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.
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.
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With