@babel/plugin-transform-async-to-generator
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
信息
该插件已包含在 @babel/preset-env 的 ES2017 预设中
在 Babel 7 中,transform-async-to-module-method 已合并至本插件
示例
输入
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();
});
安装
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-async-to-generator
yarn add --dev @babel/plugin-transform-async-to-generator
pnpm add --save-dev @babel/plugin-transform-async-to-generator
bun add --dev @babel/plugin-transform-async-to-generator
用法
通过配置文件(推荐)
无配置选项时:
babel.config.json
{
"plugins": ["@babel/plugin-transform-async-to-generator"]
}
使用配置选项时:
babel.config.json
{
"plugins": [
[
"@babel/plugin-transform-async-to-generator",
{
"module": "bluebird",
"method": "coroutine"
}
]
]
}
通过命令行
Shell
babel --plugins @babel/plugin-transform-async-to-generator script.js
通过 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-async-to-generator"],
});
注意事项
Bluebird 非 Promise 运行时错误
当对非 Promise 值使用 await 时,Bluebird 会抛出"Error: A value was yielded that could not be treated as a promise"错误。由于 Babel 无法自动处理此运行时错误,您需要手动将其转换为 Promise。
async function foo() {
- await 42;
+ await Promise.resolve(42);
}