Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现 Promise.retry 方法 #41

Open
Inchill opened this issue Sep 25, 2022 · 0 comments
Open

实现 Promise.retry 方法 #41

Inchill opened this issue Sep 25, 2022 · 0 comments

Comments

@Inchill
Copy link
Owner

Inchill commented Sep 25, 2022

// 请实现一个方法, 对传入的异步任务尝试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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant