Retry mechanism paradigm with back-off

Probably you already faced a problem when an operation fails and you need to retry it in a certain amount of time or want to try it few more times before giving up and fire an error. A simple solution would be to use functionality similar to the below piece of code:

async function retryFunction(func, timeout = 100, factor = 2, retries = 4) {
  try {
    return await func();
  } catch (err) {
    if (retries < 1) {
      throw err;
    }
    logger.warn(`Retrying function in ${timeout / 1000} seconds`);
    await sleep(timeout);
    return retryFunction(func, timeout * factor, factor, retries - 1);
  }
};

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.