-1

How can I make sure anotherFunction() is called only when all the Ajax request are done without using async: false?

$(data).each(function(index, item) {
    
    $.ajax({
        url: "someUrl.com/someData?Id=" + item.id,
        success: function(result) {
            someFunction(result);
        }
    });

    anotherFunction();
        
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Josh Adams
  • 2,113
  • 2
  • 13
  • 25
Rawland Hustle
  • 781
  • 1
  • 10
  • 16

1 Answers1

1

Use Promise.all, which will only fire the .then when all promises it is passed have completed:

let requests = [];

$(data).each(function(index, item) {

  let request = $.ajax({
    url: "someUrl.com/someData?Id=" + item.id,
    success: function(result) {
      someFunction(result);
    }
  });

  requests.push(request);

});

Promise.all(requests).then(() => anotherFunction());
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45