Using Async/Await Without Babel

Written by richardkall | Published 2017/01/29
Tech Story Tags: javascript | nodejs | web-development

TLDRvia the TL;DR App

Experimental async/await support in Node 7.

Let’s start with a simple example. Say we want to create a function that requests an URL and tells us the status code. Using ES6 promises this is what the code might look like:

With async/await we can simplify the getStatus function a bit. Instead of calling .then() we can rewrite it as a async function and await for the request to be resolved.

It will wait for the promise to resolve in a non-blocking way. However, when trying to run this with node async-await-example you will get an error.

async function getStatus (url) {^^^^^^^^SyntaxError: Unexpected token function

The good news is that async/await has landed in v8 of the JavaScript engine, which is implemented in Node 7. Async/await is added as a experimental feature and can be used with the flag --harmony-async-await.

Start using async/await today by installing Node 7 and running it with:

$ node --harmony-async-await

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!


Published by HackerNoon on 2017/01/29