Created
June 12, 2017 00:47
-
-
Save namoshizun/17920eba88de210143145fa03e8f0be1 to your computer and use it in GitHub Desktop.
implement async await using generators
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
// Helper | |
function print(obj) { | |
console.log(obj) | |
} | |
// Mimic Async-Await | |
function coRunner(feedback) { | |
let iterator = this; | |
let result = iterator.next(feedback); | |
if (result.done) { | |
return; | |
} | |
Promise.resolve(result.value).then(function(nextFeedback) { | |
coRunner.call(iterator, nextFeedback); | |
}) | |
} | |
function _async(generatorFn) { | |
let iterator = generatorFn(); | |
coRunner.call(iterator); | |
} | |
_async(function *() { | |
let nihao = yield 'nihao'; | |
print(nihao); | |
let hello = yield new Promise((resolve) => setTimeout(() => resolve('hello'), 3000)); | |
print(hello); | |
let world = yield new Promise((resolve) => setTimeout(() => resolve('world'), 1000)); | |
print(world); | |
let yoooo = yield Promise.resolve('yoooo'); | |
print(yoooo); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment