Skip to content

Instantly share code, notes, and snippets.

@lqt0223
Created July 7, 2023 12:16
Show Gist options
  • Save lqt0223/36cd5fdee8307fe2d7f6aac1141021af to your computer and use it in GitHub Desktop.
Save lqt0223/36cd5fdee8307fe2d7f6aac1141021af to your computer and use it in GitHub Desktop.
38 a simple co(async generator function runner)
function sleep(ms, message) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(message)
}, ms)
})
}
function co(fn) {
const generator = fn()
function tick(nextVal) {
return new Promise((resolve) => {
const { value, done } = generator.next(nextVal)
console.log(nextVal, 'nextVal')
if (value?.then) {
value.then((resolvedValue) => {
resolve({ value: resolvedValue, done })
tick(resolvedValue)
})
} else if (!done) {
resolve({ value, done })
return tick(value)
}
})
}
tick()
}
co(function*() {
const result0 = yield Promise.all([
sleep(1000, 'all1'),
sleep(2000, 'all2')
])
console.log(result0)
const result1 = yield sleep(1000, 'res1')
console.log(result1)
const result2 = yield sleep(2000, 0)
console.log(result2)
const result3 = yield sleep(3000)
console.log(result3)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment