@babel/plugin-proposal-async-do-expressions
async do { .. }
表达式在*异步*上下文中执行一个代码块(其中包含一个或多个语句),并且代码块内的最后一个语句完成值将成为*异步*代码的完成值。
示例
并行发出 HTTP 请求
JavaScript
Promise.all([
async do {
const result = await fetch('https://example.com/A');
await result.json()
},
async do {
const result = await fetch('https://example.org/B');
await result.json()
},
]).then(([a, b]) => {
console.log("example.com/A", a);
console.log("example.org/B", b);
})
将转换为
JavaScript
Promise.all([
(async () {
const result = await fetch('https://example.com/A');
return await result.json()
})(),
(async () {
const result = await fetch('https://example.org/B');
return await result.json()
})(),
]).then(([a, b]) => {
console.log("example.com/A", a);
console.log("example.org/B", b);
})
安装
- npm
- Yarn
- pnpm
npm install --save-dev @babel/plugin-proposal-async-do-expressions
yarn add --dev @babel/plugin-proposal-async-do-expressions
pnpm add --save-dev @babel/plugin-proposal-async-do-expressions
用法
使用配置文件(推荐)
babel.config.json
{
"plugins": ["@babel/plugin-proposal-async-do-expressions"]
}
注意:此插件会将 async do {}
转换为 ES2017 异步箭头函数 async () => {}
。如果您的目标是旧版引擎,例如 Node.js 6 或 IE 11,请同时添加 @babel/plugin-transform-async-to-generator
babel.config.json
{
"plugins": [
"@babel/plugin-proposal-async-do-expressions",
"@babel/plugin-transform-async-to-generator"
]
}
通过 CLI
Shell
babel --plugins @babel/plugin-proposal-async-do-expressions script.js
通过 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-proposal-async-do-expressions"],
});