aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/utils/PendingTask.ts
blob: 51b79fb0d6ec93e91f301469cca62cb6a6b26a45 (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
57
58
59
60
import { getLogger } from './logger';

const log = getLogger('utils.PendingTask');

export class PendingTask<T> {
  private readonly resolveCallback: (value: T) => void;

  private readonly rejectCallback: (reason?: unknown) => void;

  private resolved = false;

  private timeout: number | null;

  constructor(
    resolveCallback: (value: T) => void,
    rejectCallback: (reason?: unknown) => void,
    timeoutMs?: number,
    timeoutCallback?: () => void,
  ) {
    this.resolveCallback = resolveCallback;
    this.rejectCallback = rejectCallback;
    if (timeoutMs) {
      this.timeout = setTimeout(() => {
        if (!this.resolved) {
          this.reject(new Error('Request timed out'));
          if (timeoutCallback) {
            timeoutCallback();
          }
        }
      }, timeoutMs);
    } else {
      this.timeout = null;
    }
  }

  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 !== null) {
      clearTimeout(this.timeout);
    }
  }
}