Last active
August 5, 2024 23:45
-
-
Save adambene/b3de67803e634be8f7d6baa273b5f447 to your computer and use it in GitHub Desktop.
Coroutines and generators in JavaScript
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
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