I have a function that I call from a from a timeout that makes an ajax call. I also have a button click call that I don’t want to execute until the ajax call completes, if the ajax call is running. If the ajax call is not running, I want to run the button click code.
What is the best way to handle this? With a variable that you check to see if the ajax function is running or is there another way?
Here is my pseudo code
setTimeout(doAjax, 5000);
function doAjax() {
$.ajax({
url: "xxx.com/dosomething",
dataType: 'json',
type: 'POST',
cache: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { doSuccess() },
error: function (data, status, jqXHR) { doError() }
});
}
function myBtnClick() {
// wait for doAjax call to complete if running
}
2
Answers
The solution here is to use promises to maintain the state of your async code.
Initially, the
clickDelayPromise
will resolve immediately but once the AJAX call begins, the promise will only resolve once the request completes.You can achieve what you want by making sure that your prerequisite async operations you have are promises and, if you have an array where you store them, then you can do something like this:
Proof-of-concept: