-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncPoller.js
96 lines (79 loc) · 1.92 KB
/
AsyncPoller.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
export const POLLING_CANCELLED_ERROR_MESSAGE = 'cancelled';
export const POLLING_MAX_ATTEMPTS_ERROR_MESSAGE = 'max_attempts_reached';
export default class AsyncPoller {
action;
doneCondition;
intervalMs;
maxAttempts;
attemptCount = 1;
mapper = (result) => result;
cancelCondition = () => false;
do(action) {
this.action = action;
return this;
}
until(doneCondition) {
this.doneCondition = doneCondition;
return this;
}
while(notDoneCondition) {
this.doneCondition = (result) => !notDoneCondition(result);
return this;
}
maxAttempt(maxAttempts) {
this.maxAttempts = maxAttempts;
return this;
}
untilCancelled() {
this.doneCondition = () => false;
return this;
}
every(intervalMs) {
this.intervalMs = intervalMs;
return this;
}
map(mapper) {
this.mapper = mapper;
return this;
}
cancelledOn(cancelCondition) {
this.cancelCondition = cancelCondition;
return this;
}
async poll() {
if (
!this.action ||
!(this.doneCondition || this.whenList.length) ||
!this.intervalMs
) {
throw new Error('not initialized');
}
this._checkCancelled();
let result = await this._doAction();
while (!this.doneCondition(result)) {
if (this.maxAttempts && this.attemptCount > this.maxAttempts) {
throw new Error(POLLING_MAX_ATTEMPTS_ERROR_MESSAGE);
}
await sleep(this.intervalMs);
this._checkCancelled();
result = await this._doAction();
this.attemptCount++;
}
return result;
}
cancel() {
this.cancelCondition = () => true;
}
_checkCancelled() {
if (this.cancelCondition()) {
throw new Error(POLLING_CANCELLED_ERROR_MESSAGE);
}
}
async _doAction() {
const unmappedResult = await this.action();
return this.mapper(unmappedResult);
}
}
function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}