0

I have a function in javascript that sends a GET request using AJAX. The request either returns success or fail or in process if the job isn't complete yet. I would like to have a function to send this GET request every few seconds until the result is either success or fail and return that result. This is what I have so far but I can't get the return value since setTimeout is calling the function again. Is there a way to put this function as a promise and return the result when it's done?

function get_r(name) {
    $.ajax({
        url: "/get/" + name
    }).done(function( result ) {
        if (JSON.parse(result) === 'success') {
            return "Finished"
        }
        else if (JSON.parse(result) === 'fail') {
            return "Failed"
        }
        else {
            setTimeout(function() { get_r(name); }, 1000);
        }
    });
mysticalstick
  • 155
  • 6
  • 21

2 Answers2

0

You can await the responses in a while loop until the response is either "Finished" or "Failed". Note that because the response isn't in JSON format, JSON.parse is unnecessary:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function get_r(name) {
  while (true) {
    const result = await $.ajax({ url: "/get/" + name });
    if (result === 'success') return 'Finished';
    else if (result === 'fail') return 'Failed';
    await delay(1000);
  }
}

While this functionality is similar to your original code, it would probably be a good idea to put a limit on the number of retries (what is the server response is something like "Cannot process request at this time" rather than getting through to the backend code which returns "fail"?). This could be implemented by using a for loop instead of a while loop:

const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function get_r(name) {
  // maximum of 5 requests
  for (let i = 0; i < 5; i++) {
    const result = await $.ajax({ url: "/get/" + name });
    if (result === 'success') return 'Finished';
    else if (result === 'fail') return 'Failed';
    await delay(1000);
  }
  return 'Server unresponsive';
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I think the OP figured out how to retry, his only problem is not knowing how to manage async code, hence the dupe vote. – nicholaswmin Feb 05 '19 at 00:50
0

How about using the .then method from promises.

you can use axios, like so:

axios.get(url).then(res => //whatever you want to do with the response)

JaMo
  • 85
  • 6