Created
September 17, 2021 19:41
-
-
Save alkhe/58fa66e5be960980a803789ee83650a3 to your computer and use it in GitHub Desktop.
Coroutines in Typescript
This file contains 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 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