Skip to content

Instantly share code, notes, and snippets.

@adambene
Last active August 5, 2024 23:45
Show Gist options
  • 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