1 | // Copyright (c) Jupyter Development Team.
|
2 | // Distributed under the terms of the Modified BSD License.
|
3 | /*-----------------------------------------------------------------------------
|
4 | | Copyright (c) 2014-2017, PhosphorJS Contributors
|
5 | |
|
6 | | Distributed under the terms of the BSD 3-Clause License.
|
7 | |
|
8 | | The full license is in the file LICENSE, distributed with this software.
|
9 | |----------------------------------------------------------------------------*/
|
10 |
|
11 | /**
|
12 | * A class which wraps a promise into a delegate object.
|
13 | *
|
14 | * #### Notes
|
15 | * This class is useful when the logic to resolve or reject a promise
|
16 | * cannot be defined at the point where the promise is created.
|
17 | */
|
18 | export class PromiseDelegate<T> {
|
19 | /**
|
20 | * Construct a new promise delegate.
|
21 | */
|
22 | constructor() {
|
23 | this.promise = new Promise<T>((resolve, reject) => {
|
24 | this._resolve = resolve;
|
25 | this._reject = reject;
|
26 | });
|
27 | }
|
28 |
|
29 | /**
|
30 | * The promise wrapped by the delegate.
|
31 | */
|
32 | readonly promise: Promise<T>;
|
33 |
|
34 | /**
|
35 | * Resolve the wrapped promise with the given value.
|
36 | *
|
37 | * @param value - The value to use for resolving the promise.
|
38 | */
|
39 | resolve(value: T | PromiseLike<T>): void {
|
40 | let resolve = this._resolve;
|
41 | resolve(value);
|
42 | }
|
43 |
|
44 | /**
|
45 | * Reject the wrapped promise with the given value.
|
46 | *
|
47 | * @reason - The reason for rejecting the promise.
|
48 | */
|
49 | reject(reason: unknown): void {
|
50 | let reject = this._reject;
|
51 | reject(reason);
|
52 | }
|
53 |
|
54 | private _resolve: (value: T | PromiseLike<T>) => void;
|
55 | private _reject: (reason: any) => void;
|
56 | }
|