0

I'm trying to find a way to make one function to hold and only return its output (hold the flow) only when the async function inside it (AJAX call) have completed.

In this click event, the "prepareEstimates" function calls another function, which makes an AJAX call to an API. The ideia is that the code won't move forward until this function has completed everything there, including the AJAX call. Because it's calling the same API, I cannot have two simultaneous call using the same data (issues with the API that are out of scope from this question).

 $('#estimateBtn').on("click", function () {
        if (validateBasicEstimationForm()) {
            prepareEstimates();

                if (validateCustomEstimationForm()) {
                    prepareCustomEstimates();
                } 

});
function prepareEstimates() {

   // check if runAPI should be true or false

    if (runApi) {
        // make call here
        $.when(callAJAXFunction(path, dataForAPICalls)).done(function (result) {
          // Do stuff with the result
        });
    }
};

Then, once this prepareEstimates function has completed, it should move forward and the next one, prepareCustomEstimates, which is very similar to this function, will do the same thing.

function prepareEstimates() {

   // check if runAPI should be true or false

    if (runApi) {
        // make call here
        $.when(callAJAXFunction(path, dataForAPICalls)).done(function (result) {
          // Do other stuff with the result
        });
    }
};

and this callAJAXFunction just return an AJAX call

    // Invoke API call and get result
    return await $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: data,
        success: function (result) {
        },
        error: function () {
            console.log("error calling Api");
        }
    });
}

I tried using promise, await, and others, but I couldn't make it work, no matter what I tried.

In the end, what is happening is that the first AJAX call is fired, then right after it, the second ajax call, before the first one has completed.

Any suggestion?

Thank you

  • because the `prepareEstimates();` has to use a promise – epascarello Sep 29 '20 at 14:05
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Heretic Monkey Sep 29 '20 at 14:12
  • How can I use the promise inside the prepareEstimates? I'm kind of new to Promises – Henrique Belotto Sep 29 '20 at 15:41

0 Answers0