Last active
July 14, 2016 22:12
-
-
Save johncoder/af903a6a98a92446b1f063c5d015b70d to your computer and use it in GitHub Desktop.
generator executor
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
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!')); |
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 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