-
-
Notifications
You must be signed in to change notification settings - Fork 150
/
Copy pathpoll-action.function.ts
45 lines (39 loc) · 1.06 KB
/
poll-action.function.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
export function timeout<R>(updateIntervalMs: number, maxDurationMs: number, action: (...params: any) => Promise<R>): Promise<R> {
return new Promise<R>((resolve, reject) => {
let interval: NodeJS.Timeout;
let timerCleaned = false
function executeInterval() {
action().then(validateResult).catch(handleRejection);
}
function validateResult(result: R){
if (!result) {
interval = setTimeout(executeInterval, updateIntervalMs);
} else {
cleanupTimer();
resolve(result);
}
}
function handleRejection() {
if(!timerCleaned){
interval = setTimeout(executeInterval, updateIntervalMs);
}
}
function cleanupTimer(){
timerCleaned = true
if(maxTimeout){
clearTimeout(maxTimeout);
}
if(interval){
clearTimeout(interval);
}
}
const maxTimeout = setTimeout(
() => {
cleanupTimer();
reject(`Action timed out after ${maxDurationMs} ms`);
},
maxDurationMs
);
executeInterval()
});
}