-
-
Save camsong/b62bd110da2b759a5986 to your computer and use it in GitHub Desktop.
ES7 Async to ES6 via Babel
This file contains hidden or 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
// $ cat script.js | |
async function foo() { | |
res = await fetch("https://example.com"); | |
return res.ok; | |
} |
This file contains hidden or 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
// $ 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 |
This file contains hidden or 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
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