-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>

1
  • you need to use promise.all Commented Dec 15, 2021 at 18:55

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

3 Comments

This would be more pragmatic as let requests = $(data).map((index, item) => $.ajax(...));
@AndyRay -- good point-- this can definitely be written to be more succinct.
This is a duplicate many many times over. Please refrain from answering them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.