blob: 49d4c36c922beb0c04da242472c1ea9e4bf47fdb (
plain) (
blame)
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
|
import { getLogger } from '../logging';
const REQUEST_TIMEOUT_MS = 1000;
const log = getLogger('PendingRequest');
export class PendingRequest {
private readonly resolveCallback: (value: unknown) => void;
private readonly rejectCallback: (reason?: unknown) => void;
private readonly timeoutCallback: () => void;
private resolved = false;
private timeoutId: NodeJS.Timeout;
constructor(
resolve: (value: unknown) => void,
reject: (reason?: unknown) => void,
timeout: () => void,
) {
this.resolveCallback = resolve;
this.rejectCallback = reject;
this.timeoutCallback = timeout;
this.timeoutId = setTimeout(() => {
if (!this.resolved) {
this.reject(new Error('Request timed out'));
this.timeoutCallback();
}
}, REQUEST_TIMEOUT_MS);
}
resolve(value: unknown): void {
if (this.resolved) {
log.warn('Trying to resolve already resolved promise');
return;
}
this.markResolved();
this.resolveCallback(value);
}
reject(reason?: unknown): void {
if (this.resolved) {
log.warn('Trying to reject already resolved promise');
}
this.markResolved();
this.rejectCallback(reason);
}
private markResolved() {
this.resolved = true;
clearTimeout(this.timeoutId);
}
}
|