UNPKG

2.49 kBTypeScriptView Raw
1import {OperationOptions} from 'retry';
2
3declare class AbortErrorClass extends Error {
4 readonly name: 'AbortError';
5 readonly originalError: Error;
6
7 /**
8 Abort retrying and reject the promise.
9
10 @param message - Error message or custom error.
11 */
12 constructor(message: string | Error);
13}
14
15declare namespace pRetry {
16 interface FailedAttemptError extends Error {
17 readonly attemptNumber: number;
18 readonly retriesLeft: number;
19 }
20
21 interface Options extends OperationOptions {
22 /**
23 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.
24 */
25 readonly onFailedAttempt?: (error: FailedAttemptError) => void;
26 }
27
28 type AbortError = AbortErrorClass;
29}
30
31declare const pRetry: {
32 /**
33 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.
34
35 It doesn't retry on `TypeError` as that's a user error.
36
37 @param input - Receives the number of attempts as the first argument and is expected to return a `Promise` or any value.
38 @param options - Options are passed to the [`retry`](https://github.com/tim-kos/node-retry#retryoperationoptions) module.
39
40 @example
41 ```
42 import pRetry = require('p-retry');
43 import fetch from 'node-fetch';
44
45 const run = async () => {
46 const response = await fetch('https://sindresorhus.com/unicorn');
47
48 // Abort retrying if the resource doesn't exist
49 if (response.status === 404) {
50 throw new pRetry.AbortError(response.statusText);
51 }
52
53 return response.blob();
54 };
55
56 (async () => {
57 console.log(await pRetry(run, {retries: 5}));
58
59 // With the `onFailedAttempt` option:
60 const result = await pRetry(run, {
61 onFailedAttempt: error => {
62 console.log(`Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`);
63 // 1st request => Attempt 1 failed. There are 4 retries left.
64 // 2nd request => Attempt 2 failed. There are 3 retries left.
65 // …
66 },
67 retries: 5
68 });
69
70 console.log(result);
71 })();
72 ```
73 */
74 <T>(
75 input: (attemptCount: number) => PromiseLike<T> | T,
76 options?: pRetry.Options
77 ): Promise<T>;
78
79 AbortError: typeof AbortErrorClass;
80
81 // TODO: remove this in the next major version
82 default: typeof pRetry;
83};
84
85export = pRetry;