2

I have a function which has many different function calls having many ajax calls inside. How do I know if all the ajax calls being triggered by $("#save").click(...) are completed ?

$("#save").click(function() {

    saveUpdateSeatDetails();
    markAbsent();

    setTimeout(function() {
        location.reload();
    }, 369);
});

I tried using async: false, but I get warring suggesting it's deprecated.

I also referred How to know when all ajax calls are complete ?. However, this applies for the entire page. I want this to apply on a particular function only.

(Nothing ES6 )

  • 4
    Maybe you don't *have* to use Promises, but you *really should* if you want your code to be easily readable and maintainable. It's as simple as `Promise.all`, and if you want to serve to clients who might not support Promises, that's what polyfills are for. – CertainPerformance Apr 26 '18 at 05:34
  • Possible duplicate of [Pass in an array of Deferreds to $.when()](https://stackoverflow.com/questions/5627284/pass-in-an-array-of-deferreds-to-when) – CertainPerformance Apr 26 '18 at 05:38

1 Answers1

5

You should jQuery's Deferred (slightly different but mostly compatible with Promises), which is returned by $.ajax calls. I'm going to assume you're using $.ajax here since you used jQuery in your answer.

You'll need to update your functions to return the $.ajax calls:

function saveUpdateSeatDetails() {
    return $.ajax("http://example.com...");
}

function markAbsent() {
    return $.ajax("http://example.com...");
}

Then you can do:

$("#save").click(function() {
    $.when(saveUpdateSeatDetails(), markAbsent()).done(function() {
         alert("test")
    });
});

$.when waits for the Ajax requests to complete before executing the function.

Since this is part of jQuery 1.5+, any browser compatible with jQuery will be able to run this code (no ES6 needed).

Richard Ye
  • 685
  • 4
  • 12