Skip to content

Instantly share code, notes, and snippets.

@alkhe
Created September 17, 2021 19:41
Show Gist options
  • Save alkhe/58fa66e5be960980a803789ee83650a3 to your computer and use it in GitHub Desktop.
Save alkhe/58fa66e5be960980a803789ee83650a3 to your computer and use it in GitHub Desktop.
Coroutines in Typescript
type GeneratorFunction<T> = () => Generator<any, T, any>
export default function<T>(g: GeneratorFunction<T>): Promise<T> {
return new Promise((res, rej) => {
// create generator
const r = g()
function step(green: boolean, fulfilled: any) {
let result: IteratorResult<any, T> | null
try {
// resume with fulfilled value
result = green ? r.next(fulfilled) : r.throw(fulfilled)
} catch (err) {
// reject with unhandled error in coroutine
return rej(err)
}
const { value } = result
// convert result value to Promise
const p = value != null && value.constructor === Array
? Promise.all(value)
: Promise.resolve(value)
// if done, fulfill final value
if (result.done) return p.then(res, rej)
// otherwise continue
p.then(
x => step(true, x),
err => step(false, err)
)
}
step(true, null)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment