Tags
jQuery , AJAX
Asked 3 years ago
24 Jun 2021
Views 643
Jaiden

Jaiden posted

execute code after AJAX loop finished

execute code after AJAX loop finished
sarah

sarah
answered Apr 28 '23 00:00

Here's a possible way to rewrite the answer to avoid duplicate content:

To run code after an AJAX loop has completed, you can use promises in combination with the .done() method. Here's an example:



const promises = [];

// Loop through data and make an AJAX call for each item
data.forEach(function(item) {
  const promise = $.ajax({
    url: 'example.com/ajax',
    data: { item: item },
    dataType: 'json'
  });
  
  promises.push(promise);
});

// Wait for all promises to resolve using $.when()
$.when(...promises).done(function() {
  // This code will run after all the AJAX calls have completed
  console.log('All AJAX calls are  completed ');
});

In this example, we're using a forEach loop to iterate through data and make an AJAX call for each item. The $.ajax() method returns a promise object, which we add to the promises array.

After all promises have been added to the array, we use $.when() to wait for all of them to resolve. We use the spread syntax (...) to pass each promise in the array as a separate argument to $.when(). Once all the promises have resolved, the . done() method is called to run the code that we want to execute after the AJAX loop has completed .

By using promises, we ensure that the code inside the .done() method only runs after all AJAX calls have completed , regardless of their order or timing.
Post Answer