0

I am trying implement a retry process which should make a async call with provide time gap for N number of time. This the sample code.

async function client(){
  const options = {
    method: 'GET',
    headers: {
      'content-type': 'application/json'
    }
  }
  const resp = await axios('url://someurl.com', options);
  return resp; // returns { processingFinished: true or false}
}


export async function service() {
  let processed = false;
  let retry = 0;
  while (!processed && retry < 10) {
    // eslint-disable-next-line no-await-in-loop
    const { processingFinished } = await client();
    processed = processingFinished;
    retry++;
  }
  return processed;
}

async function controller(req, res, next){
  try{
    const value = await service();
    res.send(value);
    next();
  } catch(err){
    next(err);
  }
}

I want to have 500ms gap between each call before I do retry. Kindly help.

1

1 Answer 1

1

Your code seems okay, you can add a delay with a helper function like this:

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

use it in your retry loop:

 while (!processed && retry < 10) {
    // eslint-disable-next-line no-await-in-loop
    const { processingFinished } = await client();
    processed = processingFinished;
    retry++;
    // wait only if the loop is not finished
    if (!processed && retry < 10) await wait(500); // add this
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.