Skip to main content

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

信息

此插件包含在 @babel/preset-env 中,在 ES2017

¥This plugin is included in @babel/preset-env, in ES2017

在 Babel 7 中,transform-async-to-module-method 被合并到这个插件中

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

示例

¥Example

输入

¥In

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

输出

¥Out

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

有选择权

¥Out with options

将异步函数转换为 Bluebird 协程 (caveats)

¥Turn async functions into a Bluebird coroutine (caveats)

JavaScript
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:

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

有选项:

¥With options:

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

通过 CLI

¥Via CLI

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

通过 Node API

¥Via Node API

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

注意事项

¥Caveats

蓝鸟非 promise 运行时错误

¥Bluebird non-promise runtime error

当将 await 与非 promise 值一起使用时,Bluebird 将抛出“错误:产生的值不能被视为 promise”。由于 Babel 无法自动处理此运行时错误,因此你应该手动将其转换为 Promise。

¥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