index.d.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import {type OperationOptions} from 'retry';
  2. export class AbortError extends Error {
  3. readonly name: 'AbortError';
  4. readonly originalError: Error;
  5. /**
  6. Abort retrying and reject the promise.
  7. @param message - An error message or a custom error.
  8. */
  9. constructor(message: string | Error);
  10. }
  11. export type FailedAttemptError = {
  12. readonly attemptNumber: number;
  13. readonly retriesLeft: number;
  14. } & Error;
  15. export type Options = {
  16. /**
  17. Callback invoked on each retry. Receives the error thrown by `input` as the first argument with properties `attemptNumber` and `retriesLeft` which indicate the current attempt number and the number of attempts left, respectively.
  18. The `onFailedAttempt` function can return a promise. For example, to add a [delay](https://github.com/sindresorhus/delay):
  19. ```
  20. import pRetry from 'p-retry';
  21. import delay from 'delay';
  22. const run = async () => { ... };
  23. const result = await pRetry(run, {
  24. onFailedAttempt: async error => {
  25. console.log('Waiting for 1 second before retrying');
  26. await delay(1000);
  27. }
  28. });
  29. ```
  30. If the `onFailedAttempt` function throws, all retries will be aborted and the original promise will reject with the thrown error.
  31. */
  32. readonly onFailedAttempt?: (error: FailedAttemptError) => void | Promise<void>;
  33. /**
  34. Decide if a retry should occur based on the error. Returning true triggers a retry, false aborts with the error.
  35. It is not called for `TypeError` (except network errors) and `AbortError`.
  36. @param error - The error thrown by the input function.
  37. @example
  38. ```
  39. import pRetry from 'p-retry';
  40. const run = async () => { … };
  41. const result = await pRetry(run, {
  42. shouldRetry: error => !(error instanceof CustomError);
  43. });
  44. ```
  45. In the example above, the operation will be retried unless the error is an instance of `CustomError`.
  46. */
  47. readonly shouldRetry?: (error: FailedAttemptError) => boolean | Promise<boolean>;
  48. /**
  49. You can abort retrying using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
  50. ```
  51. import pRetry from 'p-retry';
  52. const run = async () => { … };
  53. const controller = new AbortController();
  54. cancelButton.addEventListener('click', () => {
  55. controller.abort(new Error('User clicked cancel button'));
  56. });
  57. try {
  58. await pRetry(run, {signal: controller.signal});
  59. } catch (error) {
  60. console.log(error.message);
  61. //=> 'User clicked cancel button'
  62. }
  63. ```
  64. */
  65. readonly signal?: AbortSignal;
  66. } & OperationOptions;
  67. /**
  68. Returns a `Promise` that is fulfilled when calling `input` returns a fulfilled promise. If calling `input` returns a rejected promise, `input` is called again until the max retries are reached, it then rejects with the last rejection reason.
  69. Does not retry on most `TypeErrors`, with the exception of network errors. This is done on a best case basis as different browsers have different [messages](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful) to indicate this.
  70. See [whatwg/fetch#526 (comment)](https://github.com/whatwg/fetch/issues/526#issuecomment-554604080)
  71. @param input - Receives the number of attempts as the first argument and is expected to return a `Promise` or any value.
  72. @param options - Options are passed to the [`retry`](https://github.com/tim-kos/node-retry#retryoperationoptions) module.
  73. @example
  74. ```
  75. import pRetry, {AbortError} from 'p-retry';
  76. import fetch from 'node-fetch';
  77. const run = async () => {
  78. const response = await fetch('https://sindresorhus.com/unicorn');
  79. // Abort retrying if the resource doesn't exist
  80. if (response.status === 404) {
  81. throw new AbortError(response.statusText);
  82. }
  83. return response.blob();
  84. };
  85. console.log(await pRetry(run, {retries: 5}));
  86. // With the `onFailedAttempt` option:
  87. const result = await pRetry(run, {
  88. onFailedAttempt: error => {
  89. console.log(`Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`);
  90. // 1st request => Attempt 1 failed. There are 4 retries left.
  91. // 2nd request => Attempt 2 failed. There are 3 retries left.
  92. // …
  93. },
  94. retries: 5
  95. });
  96. console.log(result);
  97. ```
  98. */
  99. export default function pRetry<T>(
  100. input: (attemptCount: number) => PromiseLike<T> | T,
  101. options?: Options
  102. ): Promise<T>;