send multiple ajax post requests at regular intervals until any one of them passed

237 Views Asked by At

I am writing a test program for website most of time the website gives 504 error. i want to write a program that can sent ajax requests to server and replace page with server response html. the process of requests is like :

  1. send 20 requests at a time if any of them got 200 response then cancell all other requests
  2. repeat step 1 after 10 seconds until any request got valid response.

currently i am making 20 ajax calls and the wait for any of them to complete using Promise.any(). the problem i am facing is that how can i manage all batches in one Promise.any() because i need to keep track of previous batch as well like if one of second batch calls completed i need to cancell all first batch calls and remaining 2nd batch calls. Hope you got my point what i want. here is the code i have done so far

var reqs = [];
async function post_page(url, i){

    var formElement = document.getElementById('form1');
    var data = new URLSearchParams(new FormData(formElement));
    data.append('continue', 'Continue');

    let controller = new AbortController();
    var req = fetch(url, {
        method: 'post',
        body: data,
    }
     ).then(response => {
      if (!response.ok) {
            return Promise.reject('not ok');
        }
      return (response, i);
  });
    reqs.push(controller);
};

var load_page = function(url){
    var promises = [];

    for(var i = 0 ; i < 10; i++){
        promises.push(post_page(url, i));
    };

     Promise.any(promises).then((value, index) => {
         reqs.splice(index,1);
         $.each(reqs, function(id, req){req.abort();})
        loadPageHtml(value);
    })
};
0

There are 0 best solutions below