Skip to content

Instantly share code, notes, and snippets.

@alextes
Last active December 27, 2016 10:05
Show Gist options
  • Save alextes/292d31bf297ead86b8a4d0defeecae00 to your computer and use it in GitHub Desktop.
Save alextes/292d31bf297ead86b8a4d0defeecae00 to your computer and use it in GitHub Desktop.
Getting Async / Await now with Babel

Async / Await with Babel.js

Natively with Node.js

As of writing this (26-12-16) Node does not support Async / Await yet. To check if it does now head over to node.green. In case you're thinking, but the harmony flag!, yes, node at this moment has a harmony flag that enables an unstable implementation of Async / Await. It is however, for good reason marked unstable. Use features behind harmony flags for testing only. Not for things that will at any point in the future be deployed.

Compiling with Babel

In short, babel lets you use next generation JavaScript today. If you want to use some language feature that is marked red on node.green or for other environments like browsers, one of these compatibility tables chances are Babel can get you there. The cost will be having to compile your source code from JavaScript to JavaScript. The difference being that some language features will be rewritten into more restricted JavaScript that is supported in your target environment.

Get me Async / Await already!

How you need to set up Babel depends on your target environment. See the babel/setup page for the many environments your code might end up in. For Node.js see the babel-cli subsection specifically. Now Babel is ready to compile. However only what we told it to compile in the babel configuration file you should have set up now. Usually .babelrc. So let's hit the babel plugins page a.k.a. the candy store. You are likely excited about the async-to-generator transform. You can add the transform as a plugin. In case you already have one of the presets that contain this transform, currently es2017 or latest, you don't need to add the transform.

Frequently Asked Questions

My build tool / test runner / IDE doesn't work and complains about regenerator-runtime missing.

You'll need babel-polyfill and require it before any code relying on async / await is evaluated.

I have a different question!

You can usually find me (alextes) on the #node.js irc channel or the NodeJS slack group. Alternatively, feel free to comment on this gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment