Skip to content

Instantly share code, notes, and snippets.

@camsong
Forked from callahad/0 - README.md
Created September 30, 2015 02:57
Show Gist options
  • Save camsong/b62bd110da2b759a5986 to your computer and use it in GitHub Desktop.
Save camsong/b62bd110da2b759a5986 to your computer and use it in GitHub Desktop.
ES7 Async to ES6 via Babel
// $ cat script.js
async function foo() {
res = await fetch("https://example.com");
return res.ok;
}
// $ babel -l asyncToGenerator script.js
let foo = _asyncToGenerator(function* () {
res = yield fetch("https://example.com");
return res.ok;
});
// Plus a definition for _asyncToGenerator(fn), found below
function _asyncToGenerator(fn) {
return function() {
var gen = fn.apply(this, arguments);
return new Promise(function(resolve, reject) {
var callNext = step.bind(null, "next");
var callThrow = step.bind(null, "throw");
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(callNext, callThrow);
}
}
callNext();
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment