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

``` javascript #569

Open
Smallnuo opened this issue Apr 8, 2022 · 2 comments
Open

``` javascript #569

Smallnuo opened this issue Apr 8, 2022 · 2 comments

Comments

@Smallnuo
Copy link

Smallnuo commented Apr 8, 2022

Promise.retry = function (promiseFn, times = 3) {
  return new Promise(async (resolve, reject) => {
    while (times--) {
      try {
        var ret = await promiseFn();
        resolve(ret);
        break;
      } catch (error) {
        if (!times) reject(error);
      }
    }
  });
};
function getProm() {
    const n = Math.random();
    return new Promise((resolve, reject) => {
        setTimeout(() =>  n > 0.9 ? resolve(n) : reject(n), 1000);
    });
}
Promise.retry(getProm);

Originally posted by @bighamD in #387 (comment)

@Smallnuo
Copy link
Author

Smallnuo commented Apr 8, 2022

因为 resolve(ret) 中的 ret 是一个 promise 对象,所以当前新建的 promise 对象的 resolve 方法是依赖这个 ret 的解决的,本身就有先后顺序,因此 async 和 await 直接去掉是不是也是可以的?

@eythy
Copy link

eythy commented May 29, 2022

不影响

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

2 participants