Skip to content

Instantly share code, notes, and snippets.

@callahad
Last active August 12, 2016 13:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save callahad/b99c83d6d9fd675137b7 to your computer and use it in GitHub Desktop.
Save callahad/b99c83d6d9fd675137b7 to your computer and use it in GitHub Desktop.
ES7 Async to ES6 via Babel

These snippets show several different ways of accomplishing the same asynchronous task: fetching a document and reporting the status code.

  1. Using callbacks.
  2. Using ES2015 Promises directly.
  3. Using ES7 Async/Await, which is just syntactic sugar for Promises.

The third example is the future, and will likely start landing in runtimes soon. You can use it today thanks to Babel, as snippets #4 and #5 show.

// $ cat callbacks.js
function foo(callback) {
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() {
var ok = this.status >= 200 && this.status <= 299;
callback(ok);
});
xhr.open("GET", "/index.html");
xhr.send();
}
// $ cat promises.js
function foo() {
return fetch("/index.html")
.then(function(res) { return res.ok; });
}
// $ cat async.js
async function foo() {
let res = await fetch("/index.html");
return res.ok;
}
// $ babel --optional asyncToGenerator async.js
// Only works in runtimes that support Promises and Generators, like Node 4.x
var foo = _asyncToGenerator(function* () {
var res = yield fetch("/index.html");
return res.ok;
});
// Plus a definition for _asyncToGenerator(fn), to emulate async/await with generators and promises.
// Source at https://github.com/babel/babel/blob/v5.8.26/packages/babel/src/transformation/templates/helper-async-to-generator.js
// $ babel async.js
// Works everywhere, but requires Regenerator from http://facebook.github.io/regenerator/
function foo() {
var res;
return regeneratorRuntime.async(function foo$(context$1$0) {
while (1) switch (context$1$0.prev = context$1$0.next) {
case 0:
context$1$0.next = 2;
return regeneratorRuntime.awrap(fetch("/index.html"));
case 2:
res = context$1$0.sent;
return context$1$0.abrupt("return", res.ok);
case 4:
case "end":
return context$1$0.stop();
}
}, null, this);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment