Created
July 7, 2023 12:16
-
-
Save lqt0223/36cd5fdee8307fe2d7f6aac1141021af to your computer and use it in GitHub Desktop.
38 a simple co(async generator function runner)
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 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