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

NOTE: This plugin is included in @babel/preset-env, in ES2017 In Babel 7, transform-async-to-module-method was merged into this plugin

Example

In

  1. async function foo() {
  2. await bar();
  3. }

Out

  1. var _asyncToGenerator = function (fn) {
  2. ...
  3. };
  4. var foo = _asyncToGenerator(function* () {
  5. yield bar();
  6. });

Out with options

Turn async functions into a Bluebird coroutine (caveats)

  1. var Bluebird = require("bluebird");
  2. var foo = Bluebird.coroutine(function*() {
  3. yield bar();
  4. });

Installation

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

Usage

Without options:

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

With options:

  1. {
  2. "plugins": [
  3. [
  4. "@babel/plugin-transform-async-to-generator",
  5. {
  6. "module": "bluebird",
  7. "method": "coroutine"
  8. }
  9. ]
  10. ]
  11. }

Via CLI

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

Via Node API

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

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.

  1. async function foo() {
  2. - await 42;
  3. + await Promise.resolve(42);
  4. }

References