# PromiseRetry

/**
 *
 * @param {函数} fn
 * @param {重试次数} times
 * @param {重试延迟ms} delay
 */
Promise.retry = function(fn, times, delay) {
  return new Promise((resolve, reject) => {
    const cb = function() {
      Promise.resolve(fn())
        .then(resolve)
        .catch((err) => {
          if (times--) {
            delay > 0
              ? setTimeout(() => {
                  cb();
                }, delay)
              : cb();
          } else {
            reject(err);
          }
        });
    };

    cb();
  });
};

function getUser() {
  return new Promise((resolve, reject) => {
    const result = Math.floor(Math.random() * 10);
    return result < 3
      ? resolve({
          id: result,
          username: "ming",
        })
      : reject(new Error(`The ${result} is greater than 3`));
  });
}

Promise.retry(getUser, 5, 10)
  .then((r) => {
    console.log(`The result is ${r.username}`);
  })
  .catch((err) => {
    console.log(err);
  });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Last Updated: 6/27/2023, 7:40:45 PM