Last active
May 23, 2016 07:55
-
-
Save gvergnaud/6173924fb8852edfc9c612dc2f8b42e0 to your computer and use it in GitHub Desktop.
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
/* ------------------------------------------------------------------------- * | |
Async / Await simple implementation with generators and promises | |
* -------------------------------------------------------------------------- */ | |
const wrap = generator => (...args) => { | |
const iterator = generator(...args) | |
const loop = ({ value: promise, done }) => { | |
if (!done) { | |
promise.then( | |
x => loop(iterator.next(x)), | |
x => loop(iterator.throw(x)) | |
) | |
} | |
} | |
loop(iterator.next()) | |
} | |
const myAsync = wrap(function* () { | |
const res = yield new Promise((res, rej) => setTimeout(() => res(10), 2000)) | |
console.log(res) | |
// => 10 | |
const second = yield new Promise((res, rej) => setTimeout(() => res(80), 1200)) | |
console.log(second) | |
// => 80 | |
}) | |
myAsync() | |
/* ----------------------------------------- * | |
With Async / Await | |
* ----------------------------------------- */ | |
const myAsync = async () => { | |
const res = await new Promise((res, rej) => setTimeout(() => res(10), 2000)) | |
console.log(res) | |
// => 10 | |
const second = await new Promise((res, rej) => setTimeout(() => res(80), 1200)) | |
console.log(second) | |
// => 80 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment