Skip to content

Instantly share code, notes, and snippets.

@adambene
Last active December 22, 2022 10:38
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save adambene/b3de67803e634be8f7d6baa273b5f447 to your computer and use it in GitHub Desktop.
Save adambene/b3de67803e634be8f7d6baa273b5f447 to your computer and use it in GitHub Desktop.
Coroutines and generators in JavaScript
function* delays() {
let a = yield delay(800, "Hello, I'm an");
console.log(a);
let b = yield delay(400, "async coroutine!");
console.log(b);
}
const coroutine = nextValue => iterator => {
const { done, value } = iterator.next(nextValue);
if (done) {
return;
}
if (value.constructor === Promise) {
value.then(promiseValue => {
coroutine(promiseValue)(iterator);
});
} else {
coroutine(value)(iterator);
}
};
const delay = (ms, result) =>
new Promise(resolve => setTimeout(() => resolve(result), ms));
coroutine()(delays());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment