index.d.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. export class AbortError extends Error {
  2. readonly name: 'AbortError';
  3. readonly originalError: Error;
  4. /**
  5. Abort retrying and reject the promise. No callback functions will be called.
  6. @param message - An error message or a custom error.
  7. */
  8. constructor(message: string | Error);
  9. }
  10. export type RetryContext = {
  11. readonly error: Error;
  12. readonly attemptNumber: number;
  13. readonly retriesLeft: number;
  14. readonly retriesConsumed: number;
  15. /**
  16. The delay in milliseconds before the next retry attempt.
  17. This is calculated based on `minTimeout`, `factor`, `maxTimeout`, and `randomize` options.
  18. Note: The actual delay may be shorter if it would exceed `maxRetryTime`.
  19. This is `0` when the retry is skipped or when no retry will occur based on the checks completed before the current callback runs.
  20. */
  21. readonly retryDelay: number;
  22. };
  23. export type Options = {
  24. /**
  25. Callback invoked on each failure. Receives a context object containing the error and retry state information.
  26. The function is called after `shouldConsumeRetry` and before `shouldRetry`, for all errors except `AbortError`.
  27. The function is not called on `AbortError`.
  28. @example
  29. ```
  30. import pRetry from 'p-retry';
  31. const run = async () => {
  32. const response = await fetch('https://sindresorhus.com/unicorn');
  33. if (!response.ok) {
  34. throw new Error(response.statusText);
  35. }
  36. return response.json();
  37. };
  38. const result = await pRetry(run, {
  39. onFailedAttempt: ({error, attemptNumber, retriesLeft, retriesConsumed, retryDelay}) => {
  40. console.log(`Attempt ${attemptNumber} failed. Retrying in ${retryDelay}ms. ${retriesLeft} retries left.`);
  41. // 1st request => Attempt 1 failed. Retrying in 1000ms. 5 retries left.
  42. // 2nd request => Attempt 2 failed. Retrying in 2000ms. 4 retries left.
  43. // …
  44. },
  45. retries: 5
  46. });
  47. console.log(result);
  48. ```
  49. The `onFailedAttempt` function can return a promise. For example, to add a [delay](https://github.com/sindresorhus/delay):
  50. @example
  51. ```
  52. import pRetry from 'p-retry';
  53. import delay from 'delay';
  54. const run = async () => { … };
  55. const result = await pRetry(run, {
  56. onFailedAttempt: async () => {
  57. console.log('Waiting for 1 second before retrying');
  58. await delay(1000);
  59. }
  60. });
  61. ```
  62. If the `onFailedAttempt` function throws, all retries will be aborted and the original promise will reject with the thrown error.
  63. */
  64. readonly onFailedAttempt?: (context: RetryContext) => void | Promise<void>;
  65. /**
  66. Decide if a retry should occur based on the context. Returning true triggers a retry, false aborts with the error.
  67. The function is called after `onFailedAttempt` and `shouldConsumeRetry`.
  68. The function is not called on `AbortError`, `TypeError` (except network errors), or if `retries` or `maxRetryTime` are exhausted.
  69. @example
  70. ```
  71. import pRetry from 'p-retry';
  72. const run = async () => { … };
  73. const result = await pRetry(run, {
  74. shouldRetry: ({error, attemptNumber, retriesLeft}) => !(error instanceof CustomError)
  75. });
  76. ```
  77. In the example above, the operation will be retried unless the error is an instance of `CustomError`.
  78. If the `shouldRetry` function throws, all retries will be aborted and the original promise will reject with the thrown error.
  79. */
  80. readonly shouldRetry?: (context: RetryContext) => boolean | Promise<boolean>;
  81. /**
  82. Decide if this failure should consume a retry from the `retries` budget.
  83. When `false` is returned, the failure will not consume a retry or increment backoff values, but is still subject to `maxRetryTime`.
  84. The function is called before `onFailedAttempt` and `shouldRetry`.
  85. The function is not called on `AbortError`.
  86. @example
  87. ```
  88. import pRetry from 'p-retry';
  89. const run = async () => { … };
  90. const result = await pRetry(run, {
  91. retries: 2,
  92. shouldConsumeRetry: ({error, retriesLeft}) => {
  93. console.log(`Retries left: ${retriesLeft}`);
  94. return !(error instanceof RateLimitError);
  95. },
  96. });
  97. ```
  98. In the example above, `RateLimitError`s will not decrement the available `retries`.
  99. If the `shouldConsumeRetry` function throws, all retries will be aborted and the original promise will reject with the thrown error.
  100. */
  101. readonly shouldConsumeRetry?: (context: RetryContext) => boolean | Promise<boolean>;
  102. /**
  103. The maximum amount of times to retry the operation.
  104. @default 10
  105. */
  106. readonly retries?: number;
  107. /**
  108. The exponential factor to use.
  109. @default 2
  110. */
  111. readonly factor?: number;
  112. /**
  113. The number of milliseconds before starting the first retry.
  114. Set this to `0` to retry immediately with no delay.
  115. @default 1000
  116. */
  117. readonly minTimeout?: number;
  118. /**
  119. The maximum number of milliseconds between two retries.
  120. @default Infinity
  121. */
  122. readonly maxTimeout?: number;
  123. /**
  124. Randomizes the timeouts by multiplying with a factor between 1 and 2.
  125. @default false
  126. */
  127. readonly randomize?: boolean;
  128. /**
  129. The maximum time (in milliseconds) that the retried operation is allowed to run.
  130. @default Infinity
  131. Measured with a monotonic clock (`performance.now()`) so system clock adjustments do not affect the limit.
  132. */
  133. readonly maxRetryTime?: number;
  134. /**
  135. You can abort retrying using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
  136. ```
  137. import pRetry from 'p-retry';
  138. const run = async () => { … };
  139. const controller = new AbortController();
  140. cancelButton.addEventListener('click', () => {
  141. controller.abort(new Error('User clicked cancel button'));
  142. });
  143. try {
  144. await pRetry(run, {signal: controller.signal});
  145. } catch (error) {
  146. console.log(error.message);
  147. //=> 'User clicked cancel button'
  148. }
  149. ```
  150. */
  151. readonly signal?: AbortSignal | undefined;
  152. /**
  153. Prevents retry timeouts from keeping the process alive.
  154. Only affects platforms with a `.unref()` method on timeouts, such as Node.js.
  155. @default false
  156. */
  157. readonly unref?: boolean;
  158. };
  159. /**
  160. 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.
  161. 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. See [whatwg/fetch#526 (comment)](https://github.com/whatwg/fetch/issues/526#issuecomment-554604080)
  162. Non-network `TypeError`s always abort retries, even if `shouldConsumeRetry` or `shouldRetry` would otherwise allow another attempt.
  163. @param input - Receives the number of attempts as the first argument and is expected to return a `Promise` or any value.
  164. @param options - Options for configuring the retry behavior.
  165. @example
  166. ```
  167. import pRetry, {AbortError} from 'p-retry';
  168. const run = async () => {
  169. const response = await fetch('https://sindresorhus.com/unicorn');
  170. // Abort retrying if the resource doesn't exist
  171. if (response.status === 404) {
  172. throw new AbortError(response.statusText);
  173. }
  174. return response.blob();
  175. };
  176. console.log(await pRetry(run, {retries: 5}));
  177. ```
  178. */
  179. export default function pRetry<T>(
  180. input: (attemptNumber: number) => PromiseLike<T> | T,
  181. options?: Options
  182. ): Promise<T>;
  183. /**
  184. Wrap a function so that each call is automatically retried on failure.
  185. @example
  186. ```
  187. import {makeRetriable} from 'p-retry';
  188. const fetchWithRetry = makeRetriable(fetch, {retries: 5});
  189. const response = await fetchWithRetry('https://sindresorhus.com/unicorn');
  190. ```
  191. */
  192. export function makeRetriable<Arguments extends readonly unknown[], Result>(
  193. function_: (...arguments_: Arguments) => PromiseLike<Result> | Result,
  194. options?: Options
  195. ): (...arguments_: Arguments) => Promise<Result>;