Daily-Interview-Question icon indicating copy to clipboard operation
Daily-Interview-Question copied to clipboard

``` javascript

Open Smallnuo opened this issue 2 years ago • 2 comments

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 https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/387#issuecomment-631855846

Smallnuo avatar Apr 08 '22 15:04 Smallnuo

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

Smallnuo avatar Apr 08 '22 15:04 Smallnuo

不影响

eythy avatar May 29 '22 07:05 eythy