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 函数实现 #14

Open
zhongs opened this issue May 9, 2020 · 0 comments
Open

Promise.retry 函数实现 #14

zhongs opened this issue May 9, 2020 · 0 comments

Comments

@zhongs
Copy link
Owner

zhongs commented May 9, 2020

const fetchData = (tryNum) => new Promise((resolve, reject) => {
  setTimeout(() => tryNum == -1 ? resolve('正确') : reject('发生错误'), 1000)
})

/**
 * 重试函数
 * @param 请求函数
 * @param 重试次数
 */
Promise.retry = async (fetchData, tryNum) => {
  try {
    return Promise.resolve(await fetchData(tryNum))
  }
  catch (err) {
    tryNum--
    return tryNum > 0 ? retry(fetchData, tryNum) : Promise.reject(err)
  }
}

Promise.retry(fetchData, 3).then(data => console.log('data', data)).catch(err => console.log('error', err))
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