-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-native-promise.ts
43 lines (41 loc) · 1.21 KB
/
create-native-promise.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
type ThenableThen<T> = Promise<T>["then"];
type ThenableThenParameters<T> = Parameters<ThenableThen<T>>;
type BroadcastFulfillment<T> = ThenableThenParameters<T>[0];
type BroadcastRejection = ThenableThenParameters<never>[1];
export const createNativePromise = async<T>() => (await ({
then: (resolve) => {
const promise = (async () => ({
then: async (broadcastFulfillment, broadcastRejection) => {
await null;
(<(value: any) => void>resolve)({
promise,
resolve: broadcastFulfillment,
reject: broadcastRejection
})
}
} as PromiseLike<T>))()
}
} as PromiseLike<{
promise: Promise<T>;
resolve: NonNullable<BroadcastFulfillment<T>>;
reject: NonNullable<BroadcastRejection>
}>));
export const createNativePromiseSync = <T>() => {
let res = null;
let rej = null;
const promise = (async () => ({
then: (broadcastFulfillment, broadcastRejection) => {
res = broadcastFulfillment;
rej = broadcastRejection
}
} as PromiseLike<T>))();
return {
promise,
resolve: res,
reject: rej
} as unknown as {
promise: Promise<T>;
resolve: NonNullable<BroadcastFulfillment<T>>;
reject: NonNullable<BroadcastRejection>
};
};