实现 retry

实现 retry

只要没有 resolve,就一直 retry

方法

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

const retryOperation = (operation, delay, times) => new Promise((resolve, reject) => {
  return operation()
    .then(resolve)
    .catch((reason) => {
      if (times - 1 > 0) {
        return wait(delay)
          .then(retryOperation.bind(null, operation, delay, times - 1))
          .then(resolve)
          .catch(reject);
      }
      return reject(reason);
    });
});

如何使用

如果没有 resolvereject,那么就每隔 1 秒重试一次,最多重试 5 秒:

retryOperation(func, 1000, 5)
  .then(console.log)
  .catch(console.log);

参考