-
Notifications
You must be signed in to change notification settings - Fork 1
/
defer.ts
40 lines (37 loc) · 969 Bytes
/
defer.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
export const PromiseState = Symbol("PromiseState");
export type Defer<T> = {
resolve(t?: T);
reject(e?);
[PromiseState]: string;
} & Promise<T>;
export function defer<T>(): Defer<T> {
let res, rej;
const promise = new Promise<T>((resolve, reject) => {
res = resolve;
rej = reject;
});
const src = { resolve: null, reject: null, [PromiseState]: "pending" };
src.resolve = (...args) => {
res(...args);
src[PromiseState] = "resolved";
};
src.reject = (...args) => {
rej(...args);
src[PromiseState] = "rejected";
};
return Object.assign(promise, src);
}
export function rejectDefer<T>(e): Defer<T> {
return Object.assign(Promise.reject(e), {
resolve: () => {},
reject: () => {},
[PromiseState]: "rejected" as "rejected"
});
}
export function resolveDefer<T>(e) {
return Object.assign(Promise.resolve(e), {
resolve: () => {},
reject: () => {},
[PromiseState]: "resolved" as "resolved"
});
}