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

async-to-generator - 图1info

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

JavaScript

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

Out

JavaScript

  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)

JavaScript

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

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-async-to-generator
  1. yarn add --dev @babel/plugin-transform-async-to-generator
  1. pnpm add --save-dev @babel/plugin-transform-async-to-generator

Usage

Without options:

babel.config.json

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

With options:

babel.config.json

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

Via CLI

Shell

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

Via Node API

JavaScript

  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