Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Async call in while loop with time interval in Nodejs

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading