Home > Back-end >  Async call in while loop with time interval in Nodejs
Async call in while loop with time interval in Nodejs

Time:08-09

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.

CodePudding user response:

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
  }
  • Related