-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
deferral.ts
60 lines (53 loc) · 1.39 KB
/
deferral.ts
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
/** @format */
import FunPromise from "./fun-promise";
import _noop from "lodash/noop";
import type { Promisable } from "./types";
/**
* A class that is an "inside-out" [[`FunPromise`]]: the `resolve` and `reject` functions
* from the callback are exposed as properties, and are therefore able to be called by
* caller's code.
*
* Note that after the first call to either `resolve` or `reject`, the underlying promise
* is settled. Any subsequent call to either `resolve` or `reject` is guaranteed to be
* a no-op.
*/
export default class Deferral<T> {
/**
* The promise whose state is determined by `resolve` and `reject`.
*/
readonly promise: FunPromise<T>;
/**
* The function used to resolve [[`promise`]].
*/
private resolver: (it: Promisable<T>) => Promisable<void> | null = null;
/**
* The function used to reject [[`promise`]].
*/
private rejector: (err: unknown) => Promisable<void> | null = null;
/**
* Resolves `promise` with the given value.
*/
resolve(it) {
this.resolver(it);
return this.promise;
}
/**
* Rejects `promise` with the given cause.
*/
reject(e: Error) {
this.rejector(e);
return this.promise;
}
/**
* Constructs a new promise and exposes its resolve
* and reject functions.
*/
constructor() {
this.promise = new FunPromise(
new Promise((resolve, reject) => {
this.resolver = resolve;
this.rejector = reject;
})
);
}
}