@babel/plugin-transform-async-to-generator
在 Babel 7 中,transform-async-to-module-method
被合并到这个插件中
¥In Babel 7, transform-async-to-module-method
was merged into this plugin
示例
¥Example
输入
¥In
async function foo() {
await bar();
}
输出
¥Out
var _asyncToGenerator = function (fn) {
...
};
var foo = _asyncToGenerator(function* () {
yield bar();
});
有选择权
¥Out with options
将异步函数转换为 Bluebird 协程 (caveats)
¥Turn async functions into a Bluebird coroutine (caveats)
var Bluebird = require("bluebird");
var foo = Bluebird.coroutine(function*() {
yield bar();
});
安装
¥Installation
- npm
- Yarn
- pnpm
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
用法
¥Usage
使用配置文件(推荐)
¥With a configuration file (Recommended)
没有选项:
¥Without options:
{
"plugins": ["@babel/plugin-transform-async-to-generator"]
}
有选项:
¥With options:
{
"plugins": [
[
"@babel/plugin-transform-async-to-generator",
{
"module": "bluebird",
"method": "coroutine"
}
]
]
}
通过 CLI
¥Via CLI
babel --plugins @babel/plugin-transform-async-to-generator script.js
通过 Node API
¥Via Node API
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