|
1 | 1 | export function timeout<R>(updateIntervalMs: number, maxDurationMs: number, action: (...params: any) => Promise<R>): Promise<R> { |
2 | 2 | return new Promise<R>((resolve, reject) => { |
3 | 3 | let interval: NodeJS.Timeout; |
4 | | - const maxTimeout = setTimeout( |
5 | | - () => { |
6 | | - clearTimeout(maxTimeout); |
7 | | - if (interval) { |
8 | | - clearTimeout(interval); |
9 | | - } |
10 | | - reject(`Action timed out after ${maxDurationMs} ms`); |
11 | | - }, |
12 | | - maxDurationMs |
13 | | - ); |
14 | | - const startInterval = () => { |
15 | | - interval = setTimeout(function intervalFunc() { |
16 | | - action().then((result) => { |
17 | | - if (!result) { |
18 | | - interval = setTimeout(intervalFunc, updateIntervalMs); |
19 | | - } else { |
20 | | - clearTimeout(maxTimeout); |
21 | | - clearTimeout(interval); |
22 | | - resolve(result); |
23 | | - } |
24 | | - }).catch(() => { |
25 | | - interval = setTimeout(intervalFunc, updateIntervalMs); |
26 | | - }); |
27 | | - }, updateIntervalMs); |
28 | | - }; |
| 4 | + let timerCleaned = false |
| 5 | + |
| 6 | + function executeInterval() { |
| 7 | + action().then(validateResult).catch(handleRejection); |
| 8 | + } |
29 | 9 |
|
30 | | - action().then((result) => { |
| 10 | + function validateResult(result: R){ |
31 | 11 | if (!result) { |
32 | | - startInterval(); |
| 12 | + interval = setTimeout(executeInterval, updateIntervalMs); |
33 | 13 | } else { |
34 | | - clearTimeout(maxTimeout); |
| 14 | + cleanupTimer(); |
35 | 15 | resolve(result); |
36 | 16 | } |
37 | | - }).catch(() => { |
38 | | - startInterval(); |
39 | | - }); |
| 17 | + } |
| 18 | + |
| 19 | + function handleRejection() { |
| 20 | + if(!timerCleaned){ |
| 21 | + interval = setTimeout(executeInterval, updateIntervalMs); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + function cleanupTimer(){ |
| 26 | + timerCleaned = true |
| 27 | + if(maxTimeout){ |
| 28 | + clearTimeout(maxTimeout); |
| 29 | + } |
| 30 | + if(interval){ |
| 31 | + clearTimeout(interval); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + const maxTimeout = setTimeout( |
| 36 | + () => { |
| 37 | + cleanupTimer(); |
| 38 | + reject(`Action timed out after ${maxDurationMs} ms`); |
| 39 | + }, |
| 40 | + maxDurationMs |
| 41 | + ); |
| 42 | + |
| 43 | + executeInterval() |
40 | 44 | }); |
41 | 45 | } |
0 commit comments