Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active August 29, 2019 15:22
Show Gist options
  • Select an option

  • Save itsMapleLeaf/437f626750957d58a401900e2d9f971d to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/437f626750957d58a401900e2d9f971d to your computer and use it in GitHub Desktop.
theoretical typed co function
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)
}
}
}
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