utils.ts 668 B

12345678910111213141516171819202122232425
  1. /**
  2. * Runs the function `fn`
  3. * and retries automatically if it fails.
  4. *
  5. * Tries max `1 + retries` times
  6. * with `retryIntervalMs` milliseconds between retries.
  7. *
  8. * From https://mtsknn.fi/blog/js-retry-on-fail/
  9. */
  10. export const retry = async <T>(
  11. fn: () => Promise<T> | T,
  12. { retries, retryIntervalMs }: { retries: number; retryIntervalMs: number },
  13. ): Promise<T> => {
  14. try {
  15. return await fn();
  16. } catch (error) {
  17. if (retries <= 0) {
  18. throw error;
  19. }
  20. await sleep(retryIntervalMs);
  21. return retry(fn, { retries: retries - 1, retryIntervalMs });
  22. }
  23. };
  24. export const sleep = (ms = 0) => new Promise((resolve) => setTimeout(resolve, ms));