-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync-await-with-generators.ts
More file actions
50 lines (40 loc) · 1.16 KB
/
async-await-with-generators.ts
File metadata and controls
50 lines (40 loc) · 1.16 KB
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
import { strict as assert } from 'assert'
function asynq(func: () => Generator) {
const iterable = func()
function awwait(result: IteratorResult<unknown>): Promise<unknown> {
if (result.done) {
return Promise.resolve(result.value)
}
if (!(result.value instanceof Promise)) {
// Nothing thenable here.
return awwait(iterable.next(result.value))
}
return (
result.value
// Things worked out fine, we can call `awwait`.
.then((value) => awwait(iterable.next(value)))
// Oops. Calling `throw` will cause an exception,
// so there's no need to continue the recursion.
.catch((error) => iterable.throw(error))
)
}
return awwait(iterable.next())
}
async function test() {
const result = await asynq(function* () {
const a = yield Promise.resolve('a')
const b = yield Promise.resolve('b')
const c = yield 'c'
return [a, b, c]
})
assert.deepStrictEqual(result, ['a', 'b', 'c'])
await asynq(function* () {
try {
yield Promise.resolve('a')
yield Promise.reject('b')
} catch (error) {
assert.deepStrictEqual(error, 'b')
}
})
}
test()