retry-if.ts 878 B

12345678910111213141516171819202122232425262728293031
  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. retryCount: number
  10. }) {
  11. let count = 0;
  12. while (count <= params.retryCount) {
  13. try {
  14. const result = await promiseProvider();
  15. if (params.retryThenIf && params.retryThenIf(result)) {
  16. count++;
  17. continue;
  18. }
  19. return result;
  20. } catch (e) {
  21. if (!params.retryCatchIf || params.retryCatchIf(e)) {
  22. count++;
  23. continue;
  24. }
  25. throw e;
  26. }
  27. }
  28. throw new Error('Maximum retry count exceeded.');
  29. }