Last active
May 5, 2022 01:29
-
-
Save infernalmaster/a07eddbd06538624699ec8473154ecb1 to your computer and use it in GitHub Desktop.
js/co like generator helper
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 coSimple(fn) { | |
| let gen = fn(); | |
| function next(asyncValue) { | |
| let { done, value } = gen.next(asyncValue); | |
| let promise = isPromise(value) ? value : Promise.resolve(value); | |
| if (done) return promise; | |
| return promise.then(value => next(value), err => gen.throw(err)); | |
| } | |
| return next(); | |
| } | |
| function isPromise(p) { | |
| if (typeof p === 'object' && typeof p.then === 'function') { | |
| return true; | |
| } | |
| return false; | |
| } | |
| coSimple(function*() { | |
| let a = yield Promise.resolve("one"); | |
| console.log(a); | |
| let b = yield "two"; | |
| console.log(b); | |
| return "three"; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment