-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaitForIt.ts
49 lines (47 loc) · 982 Bytes
/
waitForIt.ts
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { exponential } from 'backoff'
/**
* @module
*
* This module contains the function that retries a given function.
*/
/**
* Retries the given function using a backoff algorithm.
* It times out after 27.75 sec by default (9 attempts)
*
* @example Wait for a tenant to be available
* ```ts
* import { waitForIt } from "@nrfcloud/wait-for-it";
*
* const tenant = await wait_for_it<Tenant>(() =>
* repo.getByUUID(
* e.aggregateUUID,
* )
* );
* ```
*/
export const waitForIt = <A>(
fn: () => Promise<A>,
retryNumber: number = 9,
): Promise<A> =>
new Promise((resolve, reject) => {
const b = exponential({
randomisationFactor: 0,
initialDelay: 250,
maxDelay: 5000,
})
let lastErr: Error
b.failAfter(retryNumber)
b.on('ready', async () => {
try {
const res = await fn()
return resolve(res)
} catch (e) {
lastErr = e as Error
}
b.backoff()
})
b.on('fail', () => {
reject(lastErr)
})
b.backoff()
})