Created
December 28, 2018 23:50
-
-
Save francisrstokes/e6fcacb5a8c5050224093e08d05af6bb to your computer and use it in GitHub Desktop.
Async/Await in 5 lines
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 interpret = iterator => last => { | |
const {value, done} = iterator.next(last); | |
return (done) ? Promise.resolve(value) : value.then(interpret(iterator)); | |
}; | |
const asyncAwait = g => interpret(g())(); | |
// ... Usage ... | |
const addOneSoon = (x, t) => new Promise(resolve => { | |
setTimeout(() => resolve(x+1), t); | |
}); | |
asyncAwait(function* () { | |
const a = yield addOneSoon(0, 1000); | |
const b = yield addOneSoon(40, 500); | |
return a + b; | |
}).then(console.log); | |
// -> 42 (After 1.5 seconds) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
like