乐趣区

关于javascript:实现一个Promiseretry

  /**
   * 实现 Promise.retry , 重试异步函数
   * 失败后重试, 尝试指定次数后  抛出异样, reject
   */
  function fn() {const num = Math.random();
    return new Promise((resolve, reject) => {setTimeout(() => {if (num > 0.7) {resolve(num);
        } else {reject(num);
        }
      }, num * 2000)
    })
  }
  Promise.prototype.retry = (fn, times) => {
    let total = times;
    new Promise(async (resolve, reject) => {while (total--) {
        try {const res = await fn();
          console.log('执行胜利, 后果为:', res);
          resolve(res);
          break;
        } catch (err) {
          // 达到指定 times 完结循环
          if (!total) {reject(err);
          }
        }
      }
    }).catch(() => {console.log('执行实现,' + times + '次全副失败...');
    })
  }

  Promise.retry(fn, 7);
退出移动版