es7 async rocks
Oct 12, 2015
2 minutes read

In case you haven’t heard, ECMAScript 2015 is here! Formerly known as ECMAScript 6, I personally start yawning any time I hear about it because we have been waiting for so long. The great thing is; though support for it is not complete, you can use all of its features and more today! All thanks to babel.js.

My favorite feature that babel now allows you to use is actually from the ECMAScript 7. Async and await.

When I started using promises instead of plain callbacks for doing asynchronous stuff I thought things were pretty good. Little did I know the real improvement coming would be the introduction of async functions.

An async function is just a function that can stop execution to wait for a promise to resolve. You indicate that something returns a promise with the await keyword.

Check out this comparison of promises and async functions.

// promises

GetData().then(function(res) {
  doSomething(res);
}).catch(function(e) {
  // catch should be used if you don't want errors
  // to be swallowed.
  console.log(e);
});

// Async:

async function asyncGetData() {
  try {
    let res = await getData();
    doSomething(res);
  } catch (e) {
     console.log(e);
  }
}

getData();

You may ask what is so great about this. Well first, you can write async code and make it look synchronous. This makes it simpler to understand. And also you get to use the regular JavaScript try and catch statements for error handling. No more weird swallowed errors.

And thats it! Give async await a try. You won’t regret it.


Back to posts