0

How can I know that no one AJAX request is being executed right now or all AJAX requests are completed? I need to write an if statement. I need js native or jquery. Like:

if(```no ajax pending```){
   //do some
}

Thanks!

hamaronooo
  • 471
  • 4
  • 20
  • If you are using `fetch` or `axios` library, those returns promise. You can check `Promise.allSettled(array of promises)`. – Vivek Bani May 29 '21 at 17:08
  • @RajdeepDebnath I don't use that :( – hamaronooo May 29 '21 at 17:09
  • You need to create and monitor a sort of ajax queue ... this thread may help you https://stackoverflow.com/questions/4785724/queue-ajax-requests-using-jquery-queue – Fennec May 29 '21 at 17:09

2 Answers2

4

You can set up events that track ajax requests in jquery

https://api.jquery.com/ajaxstart/

https://api.jquery.com/ajaxstop

let ajaxRunning = false ;

$( document ).ajaxStart(function() {
     ajaxRunning = true;
}).ajaxStop(function() {
     ajaxRunning = false;
});

if (!ajaxRunning) {
   // nothin doin
}

ajaxStop gets tripped when all requests have been completed

Kinglish
  • 23,358
  • 3
  • 22
  • 43
3

Make a wrapper around fetch or $.ajax or whichever you use that adds each request made to a Set, and check the set's size.

const requests = new Set();
const makeReq = (...args) => {
    const initialRequest = fetch(...args);
    const bodyRequest = request
        .then(res => res.text())
        .finally(() => {
            requests.delete(bodyRequest);
        });
    requests.add(bodyRequest);
    return initialRequest;
};

Then, when making a request, always use makeReq instead of fetch. No jQuery required.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320