-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-promise-callback.ts
55 lines (50 loc) · 1.82 KB
/
create-promise-callback.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
type ThenableThenParameters<T> = Parameters<Promise<T>["then"]>;
type BroadcastFulfillment<T> = ThenableThenParameters<T>[0];
type BroadcastRejection = ThenableThenParameters<never>[1];
var resolved = Promise.resolve();
export function createPromiseAsync<T>(passResult: (promise: Promise<T>, ...args: ThenableThenParameters<T>) => void) {
var promise = new Promise<T>(function (...args) {
resolved.then(() => passResult(promise, ...args)) // queueMicrotask to make sure promise has been initialized
});
};
export function createPromiseSync<T>(passResult: (promise: Promise<T>, ...args: ThenableThenParameters<T>) => void) {
var arg: null | ThenableThenParameters<T> = null;
var promise = new Promise<T>(function (...args) {
arg = args
});
passResult(promise, ...<ThenableThenParameters<T>><unknown>arg)
};
export function createPromisePromised<T>() {
return new Promise<{
promise: Promise<T>;
resolve: NonNullable<BroadcastFulfillment<T>>;
reject: NonNullable<BroadcastRejection>
}>(function (resolve) {
var promise = new Promise<T>(function (broadcastFulfillment, broadcastRejection) {
resolve(resolved.then(function () { // queueMicrotask to make sure promise has been initialized
return {
promise,
resolve: broadcastFulfillment,
reject: broadcastRejection
};
}))
})
})
};
export function createPromise<T>() {
var res: BroadcastFulfillment<T> = null;
var rej: BroadcastRejection = null;
var promise = new Promise<T>(function (broadcastFulfillment, broadcastRejection) {
res = broadcastFulfillment;
rej = broadcastRejection
});
return {
promise,
resolve: res,
reject: rej
} as unknown as {
promise: Promise<T>;
resolve: NonNullable<BroadcastFulfillment<T>>;
reject: NonNullable<BroadcastRejection>
};
};