Skip to content

Instantly share code, notes, and snippets.

@kl0tl
Created December 14, 2014 17:11
Show Gist options
  • Save kl0tl/4c4982756c1ce67ea97d to your computer and use it in GitHub Desktop.
Save kl0tl/4c4982756c1ce67ea97d to your computer and use it in GitHub Desktop.
ES7 async functions with ES6 generators and promises
/*
ES7
```
async function f() {
await ...
}
```
ES6
```
const f = async(function* () {
yield ...
});
```
*/
function async(f) {
return function () {
let generator = f.apply(this, arguments);
return new Promise((resolve, reject) => {
let onValue = generator.next.bind(generator);
let onError = generator.throw.bind(generator);
(function step(callback) {
let next;
try {
next = callback();
} catch (err) {
return reject(err);
}
if (next.done) resolve(next.value);
else if (next.value && next.value.then) Promise.resolve(next.value)
.then((value) => step(() => onValue(value)), (err) => step(() => onError(err)));
else step(() => onValue(value));
}(onValue));
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment