1

I am trying to do ajax call recursively to check whether web service is available or not. Here is my code

function checkWebService() {
            console.log("function called")
            $.ajax({
                url:  "localhost:8085/login/checkWebServiceIsRunning",
                type: 'GET',
                success: (response) => {
                    console.log("success")
                },
                error: (jqXHR, textStatus, errorThrown) => {
                console.log("error")
                    setTimeout(() => {
                        checkWebService()
                    }, 1000)
                }
            })

        }

As my service is not running initially, the code from error block gets executed but after two or three times, the ajax call gets stuck, it neither goes in success nor in error.

Then I tried putting timeout in ajax code, so it gave timeout error, but even if the web service is available and server side code gets executed without any delay, ajax gives timeout issue.

Can someone help on what could be going wrong here.

kailashdesiti
  • 165
  • 1
  • 13
  • Does this help?https://stackoverflow.com/questions/68594022/how-to-keep-calling-a-api-once-a-specific-field-of-response-is-ready – ikhvjs Aug 30 '21 at 07:44
  • Maybe this post will help you: https://stackoverflow.com/questions/9350746/using-settimeout-with-ajax-calls/9351062 – Bernhard Beatus Aug 30 '21 at 07:54

1 Answers1

1

You can use a while loop and async/await to get the response.

Also, you can add a variable count for the attempt to prevent infinite loop.

Furthermore, a wait function is added to delay each call to not utilize the program.

Note: errorCode:789 is just an example to catch the max attempt error. you can define your own.

const wait = ms => new Promise((resolve, reject) => setTimeout(resolve, ms));

async function checkWebService() {
  const MAX_ATTEMPT = 20;
  let attempt = 0;
  while (true) {
    try {
      attempt++;

      if (attempt > MAX_ATTEMPT) throw { errorCode: "789" };

      const response = await $.ajax({
        url: "localhost:8085/login/checkWebServiceIsRunning",
        type: "GET",
      });

      return response;
    } catch (err) {
      if (err.errorCode === "789") {
        throw new Error("Exceed Max. attempt.");
      }

      console.log(err);

      await wait(1000);

      continue;
    }
  }
}

checkWebService().then(console.log).catch(console.log);

ikhvjs
  • 5,316
  • 2
  • 13
  • 36