Skip to main content

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

info

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

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

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

示例​

🌐 Example

在

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

出

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

没有其他选择了

将异步函数转换为 Bluebird 协程(注意事项)

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