1. Code implementation

The overall difficulty of this problem is not difficult, just need to implement a loop.

The first thought was to write a recursion, but since this was an extension based on Promise, async came to mind so that the implementation code would be more readable.

Promise.retry = async (promiseFunc, maxTimes = 3) => {let result;
  while(maxTimes > 0) { --maxTimes; // Create a new promise to take over the target promise's resolve and reject await new promise ((res, Rej) => {promiseFunc(). Then ((result1) => {maxTimes = 0; result = result1; res(); }).catch((e) => {// Fail to check whether there are still retriesif (maxTimes === 0) {
            rej(e);
          } else{ res(); }}); }); }return result;
};
Copy the code

2. Code testing

describe("Implement promise. retry, resolve after success, retry after failure, reject after a certain number of attempts.", () = > {test("All failure", () = > {let testFunc = jest.fn(() => Promise.reject());
    Promise.retry(testFunc).catch((e) => {
      expect(testFunc).toHaveBeenCalledTimes(3);
    });
  });
  test("Twice successful", () = > {let time = 0;
    let testFunc = jest.fn(() =>
      ++time < 2 ? Promise.reject() : Promise.resolve()
    );
    return Promise.retry(testFunc).then(() => {
      expect(testFunc).toHaveBeenCalledTimes(2);
    });
  });
});
Copy the code