Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Last active May 23, 2016 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gvergnaud/6173924fb8852edfc9c612dc2f8b42e0 to your computer and use it in GitHub Desktop.
Save gvergnaud/6173924fb8852edfc9c612dc2f8b42e0 to your computer and use it in GitHub Desktop.
/* ------------------------------------------------------------------------- *
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