Skip to content Skip to sidebar Skip to footer

Generic Promise Retry Logic

I am trying to figure out how to create a generic retry function that exponentially backs off for any promise passed to it. It looks like everything is working except for a couple

Solution 1:

Here is a working example

/**
 * Function to retry
 */functionretry(func, max, time) {
  returnnewPromise((resolve, reject) => {
    apiFunction()
      .then(resolve)
      .catch(err => {
        if (max === 0) {
          returnreject(err);
        } else {
          setTimeout(function() {
            retry(func, --max, time * 2)
              .then(resolve)
              .catch(reject);
          }, time);
        }
      });
  });
}

/**
 * Function to test out
 */constapiFunction = () => newPromise((resolve, reject) => {
  const rand = Math.random();

  if (rand >= 0.8) {
    console.log('Works');
    
    resolve('hey');
  } else {
    console.log('fail');
    
    reject(newError('oh noes'));
  }
});

retry(apiFunction, 5, 10)
  .then(() =>console.log('all done ok'))
  .catch(() =>console.log('all done error'));

Post a Comment for "Generic Promise Retry Logic"