-
-
Save cakesmith/3734366960864c91324fa8b7395c517c to your computer and use it in GitHub Desktop.
Coroutines and generators in JavaScript
This file contains hidden or 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
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