Home > database >  polling function for api in javascript
polling function for api in javascript

Time:06-09

var startTime = 0;
var Id;

const refresh = async() => {
  if (startTime >= 10) {
    return
  }
  Id = await axios.get(`url`, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  }).then(res => {
    console.log("error", res.data)
    if (res.data == 'READY') {
      return res.data
    } else if (res.data == 'PENDING') {
      startTime  = 1
      setTimeout(refresh, 1000);
    }
    return null;
  }).catch(e => {
    return null;
  });

}

const wait = await refresh();

if (!Id) {
  return failure(400, "eroror")
}

///rest of the code to execute

the problem here am facing is , const wait = await refresh(); this line gets ignore first time and it executes if condition and the refresh function polling work

but what I want is refresh function to poll every second until it get ready status till 10 seconds only

CodePudding user response:

Mixing setTimeout callback-based code with await is challenging to get right. I would recommend using await for everything, including the delay, by wrapping the setTimeout into a Promise:

const refresh = async() => {
  for(let i = 0; i < 10; i  ) {
    try {
      let res = await axios.get(`url`, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      });
      console.log("error", res.data)
      if (res.data == 'READY') {
        return res.data
      }
    } catch(e) {}
    await new Promise(resolve => setTimeout(resolve, 1000));
  }
}

const Id = await refresh();
if (!Id) {
  return failure(400, "eroror")
}

CodePudding user response:

Your setTimeout(refresh, 1000); breaks the Promise chain, so your const wait = await refresh(); will never wait for any subsequent request if the status was pending.

In an async function you can use loops and await in the loop. And you can also add a sleep in there to wait a certain amount of time.

So there is no need to have any kind of recursion.

// check the link in the text for more details
function sleep(time) {
  return new Promise(resolve => setTimeout(resolve, time))
}

const refresh = async(maximumTries) => {
  let tryCount = 0;

  // loop until you reached the maximum amount of tries
  while (tryCount < maximumTries) {
    // do the request if it axios.get throws an error
    // no further try is done, if that is not desired
    // use try - catch here
    let res = await axios.get(`url`, {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    })

    if (res.data == 'READY') {
      // if ready do an early out and return the data
      return res.data
    }

    // I would not test for "res.data == 'PENDING'" here
    // because if res.data is not neither `PENDING` not `READY`
    // your code will hang.
    // if it is not ready increas the try count
    tryCount  ;
    // wait for 1000ms
    await sleep(1000);

  }

  // throw an error here as the maximum try count was reached
  throw new Error('maximum try count reached');

}

try {
  const Id = await refresh(10);


  if (!Id) {
    return failure(400, "eroror")
  }
} catch (err) {
  console.dir(err)
}

  • Related