Babel
  • Docs
  • Setup
  • Try it out
  • Videos
  • Blog
  • Donate
  • Team
  • GitHub
Edit

@babel/plugin-transform-async-to-generator

In Babel 7, transform-async-to-module-method was merged into this plugin

Example

In

async function foo() {
  await bar();
}

Out

var _asyncToGenerator = function (fn) {
  ...
};
var foo = _asyncToGenerator(function* () {
  yield bar();
});

Out with options

Turn async functions into a Bluebird coroutine (caveats)

var Bluebird = require("bluebird");

var foo = Bluebird.coroutine(function* () {
  yield bar();
});

Installation

npm install --save-dev @babel/plugin-transform-async-to-generator

Usage

With a configuration file (Recommended)

Without options:

{
  "plugins": ["@babel/plugin-transform-async-to-generator"]
}

With options:

{
  "plugins": [
    ["@babel/plugin-transform-async-to-generator", {
      "module": "bluebird",
      "method": "coroutine"
    }]
  ]
}

Via CLI

babel --plugins @babel/plugin-transform-async-to-generator script.js

Via Node API

require("@babel/core").transform("code", {
  plugins: ["@babel/plugin-transform-async-to-generator"]
});

Caveats

Bluebird non-promise runtime error

When using await with non-promise values, Bluebird will throw "Error: A value was yielded that could not be treated as a promise". Since Babel cannot automatically handle this runtime error, you should manually transform it to a promise.

async function foo() {
-  await 42;
+  await Promise.resolve(42);
}

References

  • Proposal: Async Functions for ECMAScript
  • Example
  • Installation
  • Usage
    • With a configuration file (Recommended)
    • Via CLI
    • Via Node API
  • Caveats
    • Bluebird non-promise runtime error
  • References
Babel
Docs
Learn ES2015
Community
VideosUser ShowcaseStack OverflowSlack ChannelTwitter
More
BlogGitHub OrgGitHub RepoWebsite RepoOld 6.x SiteOld 5.x Site