aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/utils/PendingTask.ts
blob: 80d1a346fda2ae6ede8e6222914721d6e581d811 (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
61
62
/*
 * SPDX-FileCopyrightText: 2021-2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

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;
    }
  }
}