There is a proposal for introducing C# style async-await
. I know Babel.js transpiles ES6 to ES5, but is there any way to make it transpile async-await to ES5
?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Perhaps even more up-to-date now; just put the babel stuff in a separate file:
See my code at how-can-i-use-es2016-es7-async-await-in-my-acceptance-tests-for-a-koa-js-app for some more details.
The approved answer seems to be outdated now. The experimental flag has been deprecated in favor of stage.
http://babeljs.io/blog/2015/03/31/5.0.0/#experimental-option
Stage 0
Stage 1
Stage 2 (Stage 2 and above are enabled by default)
This solution may have changed since (Feb 25 Felix Kling) or perhaps there is still more than one way to use async await.
What worked for us was to run Babel like so
I got this working as-of today by doing an additional
npm install babel-preset-stage-0
and using it likeSee
Babel v6
As of Babel v6, Babel doesn't contain any transformers itself anymore. You have to explicitly specify any feature you want to transform.
Presets - non ES2015 environment
The quickest way to get this working is to use presets which already contain the set of plugins needed to transform ES2015 and newer proposals. For
async
, you will need thees2015
andes2017
presets and theruntime
plugin (don't forget to installbabel-runtime
as described in the documentation):Presets - ES2015 environment
If you run the code in an environment that supports ES2015 (more specifically, generators and Promises), then all you need is the es2017 preset:
Custom
To only transform the
async
functions, you will need the following plugins.syntax-async-functions
is needed in any every case to be able to parse async functionsIn order to run the async function, you either need to use
transform-async-to-generator
: Converts theasync
function into a generator. This will use Babel's own "co-routine" implementation.transform-async-to-module-method
: Also converts theasync
function to a generator, but passes it to the module and method specified in the configuration instead of Babel's own method. This allows you to use external libraries such asbluebird
.If your code runs in an environment that supports generators, then there is nothing left to do. However, if the target environment does not support generators, you will also have to transform the generator. This is done via the
transform-regenerator
transform. This transform depends on runtime functions, so you will also need Babel'stransform-runtime
transform (+ thebabel-runtime
package).Examples:
Async to generator
Async to module method
Async to generator + regenerator
Babel v4 and older
Yes, you have to enable the experimental transformers. Babel uses regenerator.