-
-
Save asvny/fc898db988a4b74455c3 to your computer and use it in GitHub Desktop.
Promises + generators
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
async(function*() { | |
console.log('start'); | |
yield asyncFunction(); | |
var value = yield asyncFunction(); | |
console.log('value', value); | |
}); | |
function asyncFunction() { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
console.log('lalala'); | |
resolve('123'); | |
}, 5000); | |
}); | |
} | |
function async(genFunc) { | |
var gen = genFunc(); | |
function step(value) { | |
var next = gen.next(value); | |
var promise = next.value; | |
return promise | |
.then((v) => { | |
if (!next.done) { | |
step(v); | |
} | |
}) | |
.catch((e) => gen.throw(e)); | |
} | |
return step(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment