retry-if.ts 952 B

12345678910111213141516171819202122232425262728293031323334
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. export async function retryIf<T>(promiseProvider: () => Promise<T>, params: {
  7. retryThenIf?: (result: T) => boolean,
  8. retryCatchIf?: (error: any) => boolean,
  9. onRetry?: () => void,
  10. retryCount: number
  11. }) {
  12. let count = 0;
  13. while (count <= params.retryCount) {
  14. try {
  15. if (count > 0) params.onRetry?.();
  16. const result = await promiseProvider();
  17. if (params.retryThenIf && params.retryThenIf(result)) {
  18. count++;
  19. continue;
  20. }
  21. return result;
  22. } catch (e) {
  23. if (!params.retryCatchIf || params.retryCatchIf(e)) {
  24. count++;
  25. continue;
  26. }
  27. throw e;
  28. }
  29. }
  30. throw new Error('Maximum retry count exceeded.');
  31. }