Skip to content

Instantly share code, notes, and snippets.

@johncoder
Last active July 14, 2016 22:12
Show Gist options
  • Save johncoder/af903a6a98a92446b1f063c5d015b70d to your computer and use it in GitHub Desktop.
Save johncoder/af903a6a98a92446b1f063c5d015b70d to your computer and use it in GitHub Desktop.
generator executor
const context = {
sayHello: (message) => console.log(`hello, world! ${message}`)
};
function *doSomething() {
yield 1;
yield 2;
this.sayHello('about to yield!');
const three = yield new Promise((resolve, reject) => {
setTimeout(() => resolve(3), 1000);
});
this.sayHello(`done yielding!, got ${three}`);
}
executeGenerator(doSomething, context)
.then(() => console.log('done!'));
function executeGenerator(generator, context) {
return new Promise(function (resolve, reject) {
var iterator = generator.call(context);
var current;
function iterate(val) {
current = iterator.next(val);
if (current.done) {
resolve(current.value);
} else {
if (current.value && 'then' in current.value) {
current.value.then(iterate);
} else {
setImmediate(() => {
iterate(current.value);
});
}
}
}
iterate();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment