Skip to content

Instantly share code, notes, and snippets.

@infernalmaster
Last active May 5, 2022 01:29
Show Gist options
  • Select an option

  • Save infernalmaster/a07eddbd06538624699ec8473154ecb1 to your computer and use it in GitHub Desktop.

Select an option

Save infernalmaster/a07eddbd06538624699ec8473154ecb1 to your computer and use it in GitHub Desktop.
js/co like generator helper
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