-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathretry.ts
More file actions
27 lines (26 loc) · 822 Bytes
/
retry.ts
File metadata and controls
27 lines (26 loc) · 822 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import runLater from "./runLater.js";
export default function retry<T = any>(
op: () => Promise<T>,
delaySeconds: number,
retries: number,
onRetry: (e: any, retries: number) => any,
shouldRetry: (e: any) => boolean = () => true
): Promise<T> {
return new Promise<T>((resolve, reject) => {
resolve(
op().then(
(result) => result,
(e) => {
if (retries > 0 && shouldRetry(e)) {
onRetry(e, retries);
return runLater(delaySeconds * 1000, () =>
retry(op, delaySeconds, retries - 1, onRetry)
);
} else {
throw e;
}
}
)
);
});
}