Last active
August 29, 2019 15:22
-
-
Save itsMapleLeaf/437f626750957d58a401900e2d9f971d to your computer and use it in GitHub Desktop.
theoretical typed co function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type CoGen<R> = { | |
| next(): IteratorYieldResult<undefined> | |
| next<T>(value: T): IteratorResult<Promise<T>, R> | |
| } | |
| async function co<R>(genfn: () => CoGen<R>): Promise<R> { | |
| const it = genfn() | |
| let result: IteratorResult<unknown, R> = it.next() | |
| while (true) { | |
| if (result.done) { | |
| return result.value | |
| } else { | |
| result = it.next(await result.value) | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| async function test() { | |
| const result = await co(function* test() { | |
| const value = yield Promise.resolve(123) | |
| return String(value) | |
| }) | |
| assert(result === '123') | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment