blob: d0b24c1fef9f28a5f3fca0a9d4c0c8ef700e9247 (
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
56
|
import TimeoutError from './TimeoutError';
import getLogger from './getLogger';
const log = getLogger('utils.PendingTask');
export default class PendingTask<T> {
private readonly resolveCallback: (value: T) => void;
private readonly rejectCallback: (reason?: unknown) => void;
private resolved = false;
private timeout: number | undefined;
constructor(
resolveCallback: (value: T) => void,
rejectCallback: (reason?: unknown) => void,
timeoutMs: number | undefined,
timeoutCallback?: (() => void) | undefined,
) {
this.resolveCallback = resolveCallback;
this.rejectCallback = rejectCallback;
this.timeout = setTimeout(() => {
if (!this.resolved) {
this.reject(new TimeoutError());
timeoutCallback?.();
}
}, timeoutMs);
}
resolve(value: T): 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');
return;
}
this.markResolved();
this.rejectCallback(reason);
}
private markResolved() {
this.resolved = true;
if (this.timeout !== undefined) {
clearTimeout(this.timeout);
this.timeout = undefined;
}
}
}
|