-
Notifications
You must be signed in to change notification settings - Fork 13
/
promiseRepeater.ts
70 lines (59 loc) · 2.03 KB
/
promiseRepeater.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright 2020-2020 The Mandarine.TS Framework authors. All rights reserved. MIT license.
// Credits: https://github.com/jakedeichert/promise-repeater
/**
* This class serves a promise repeater which will re-try your promise until they are successfully resolved or the max attempt limit has been reached.
*
* `await new PromiseRepeater(promiseFunc).maxAttempts(5).start();`
* `await new PromiseRepeater(promiseFunc).maxAttempts(5).delay(1000).start();`
* `await new PromiseRepeater(promiseFunc).unlimitedAttempts().delay(1000).start();`
*/
export class PromiseRepeater {
private config = {
maxAttempts: 1,
delayBetweenAttemptsMs: 0,
};
private state = {
attempts: 0,
};
constructor(private readonly promiseFunc: () => Promise<any>) {
}
public maxAttempts(attempts: number): PromiseRepeater {
this.config.maxAttempts = attempts;
return this;
}
public unlimitedAttempts(): PromiseRepeater {
this.config.maxAttempts = Infinity;
return this;
}
public delay(delayBetweenAttemptsMs: number): PromiseRepeater {
this.config.delayBetweenAttemptsMs = delayBetweenAttemptsMs;
return this;
}
public start(): Promise<any> {
return this.attempt();
}
public async attempt(): Promise<any> {
this.state.attempts++;
let result = undefined;
try {
result = await this.promiseFunc();
} catch (error) {
if (this.state.attempts === this.config.maxAttempts) {
throw error;
}
// Failed attempt. Delay and then try again.
if (this.config.delayBetweenAttemptsMs) {
await this.sleep(this.config.delayBetweenAttemptsMs);
}
result = await this.attempt();
}
return result;
}
private sleep(timeoutMs: number): Promise<void> {
return new Promise((resolve): void => {
setTimeout(() => {
resolve();
}, timeoutMs);
});
}
}