Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cakesmith/3734366960864c91324fa8b7395c517c to your computer and use it in GitHub Desktop.
Save cakesmith/3734366960864c91324fa8b7395c517c 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