-
Notifications
You must be signed in to change notification settings - Fork 2
/
await-with-generators.ts
51 lines (42 loc) · 1.11 KB
/
await-with-generators.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
// Runs a generator function with async/await semantics in place of fn*/yield
// keywords. #iterator #promise #rewrite
import { Deferred } from "./deferred.js"
export function asyncFn<T, P extends any[], R>(
fn: (this: T, ...params: P) => Iterator<unknown, R, any>,
) {
return function (this: T, ...params: P): Deferred<R> {
const deferred = new Deferred<R>()
const iterator = fn.call(this, ...params)
let nextVal: any
function iterate() {
const { done, value } = iterator.next(nextVal)
if (done) {
deferred.resolve(value)
return
}
if (
typeof value == "object" &&
value &&
"then" in value &&
typeof value.then == "function"
) {
try {
Deferred.resolve(value).then((value) => {
nextVal = value
iterate()
})
} catch (error) {
iterator.throw?.(error)
}
} else {
nextVal = value
iterate()
}
}
iterate()
return deferred
}
}
export function runAsync<R>(fn: () => Iterator<unknown, R, any>) {
return asyncFn(fn)()
}