-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.ts
114 lines (97 loc) · 2.59 KB
/
index.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/// <reference types="./missing-types" />
import { uvRun } from "./build/Release/binding.node";
export { uvRun };
/**
* Run tasks in the event loop until the `pred` returns true.
*
* @param pred A function that returns boolean loop condition.
*/
export function loopWhile(pred: () => boolean) {
while (pred()) {
process._tickCallback();
if (pred()) uvRun();
}
}
/**
* Run micro task callbacks until the queue has been exhausted,
* then run all macro tasks callbacks (no nesting).
*/
export function runLoopOnce() {
process._tickCallback();
uvRun(); // Macro task should be run after microtasks.
}
/**
* Determine whether the value is a Promise.
*
* @see https://promisesaplus.com/
*/
function isThenable<T>(value: any): value is PromiseLike<T> {
return typeof value?.then === "function";
}
type Callback<R> = (error: unknown, result: R) => void;
type CallbackArgs<A extends any[], R> = [...args: A, cb: Callback<R>];
/**
* A generic replacement of callback-style function type.
*/
type Fn<T, A extends any[], R> = (this: T, ...args: CallbackArgs<A, R>) => void;
// Can't use enum as async-to-sync breaks the control flow analyzing.
const Pending = 0;
const Fulfilled = 1;
const Rejected = 2;
/**
* Generic wrapper of async function with conventional API signature
* `function (...args, (error, result) => {})`.
*
* Returns `result` and throws `error` as exception if not null.
*
* @param fn the original callback style function
* @return the wrapped function
*/
export function deasync<T, A extends any[], R>(fn: Fn<T, A, R>) {
return function (this: T, ...args: A) {
let state = Pending;
let resultOrError: unknown;
args.push((err: unknown, res: R) => {
if (err) {
resultOrError = err;
state = Rejected;
} else {
resultOrError = res;
state = Fulfilled;
}
});
fn.apply(this, args as any);
loopWhile(() => state === Pending);
if (state === Rejected) {
throw resultOrError;
} else {
return resultOrError as R;
}
};
}
/**
* Similar with the keyword `await` but synchronously.
*
* @param promise A Promise or any value to wait for
* @return Returns the fulfilled value of the promise, or the value itself if it's not a Promise.
*/
export function awaitSync<T>(promise: T) {
let state = Pending;
let resultOrError: unknown;
if (!isThenable(promise)) {
return promise as Awaited<T>;
}
promise.then(res => {
resultOrError = res;
state = Fulfilled;
}, err => {
resultOrError = err;
state = Rejected;
});
loopWhile(() => state === Pending);
if (state === Rejected) {
throw resultOrError;
} else {
return resultOrError as Awaited<T>;
}
}