We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
// 请实现一个方法, 对传入的异步任务尝试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)
运行结果如下:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
// 请实现一个方法, 对传入的异步任务尝试n次
// 若异步任务小于等于n次执行的某次为fullfilled, 则返回这次成功的结果
// 若异步任务n次执行均为rejected, 则返回最后的一次错误
运行结果如下:
The text was updated successfully, but these errors were encountered: