fe-notes icon indicating copy to clipboard operation
fe-notes copied to clipboard

实现 Promise.retry 方法

Open Inchill opened this issue 3 years ago • 0 comments

// 请实现一个方法, 对传入的异步任务尝试n次 // 若异步任务小于等于n次执行的某次为fullfilled, 则返回这次成功的结果 // 若异步任务n次执行均为rejected, 则返回最后的一次错误

async function tryNTimes (asyncFn, n = 5) {
  let err
  let count = 1

  while (n--) {
    try {
      console.log(`第${count++}次尝试`)
      const ret = await asyncFn()
      return Promise.resolve(ret)
    } catch (e) {
      err = e
      continue
    }
  }

  return Promise.reject(err)
}

function task () {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 生成一个[0, 10] 的整数
      let random = Math.floor(Math.random() * 11)
      console.log('生成的随机数:', random)
      if (random < 2) {
        console.log('任务成功')
        resolve(random)
      } else {
        reject(new Error('任务失败'))
      }
    }, 1000)
  })
}

tryNTimes(task)

运行结果如下:

Screen Shot 2022-09-25 at 16 06 10

Inchill avatar Sep 25 '22 08:09 Inchill