@babel/plugin-transform-async-to-generator
資訊
此外掛程式包含在 @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
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
用法
使用設定檔 (建議)
無選項
babel.config.json
{
"plugins": ["@babel/plugin-transform-async-to-generator"]
}
使用選項
babel.config.json
{
"plugins": [
[
"@babel/plugin-transform-async-to-generator",
{
"module": "bluebird",
"method": "coroutine"
}
]
]
}
透過 CLI
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 執行時期錯誤
當使用 await
與非 Promise 值時,Bluebird 會擲回「錯誤:產生一個無法視為 Promise 的值」。由於 Babel 無法自動處理此執行時期錯誤,您應手動將其轉換為 Promise。
async function foo() {
- await 42;
+ await Promise.resolve(42);
}