Skip to main content

@babel/plugin-proposal-async-do-expressions

async do { .. } 表达式会在一个 异步 上下文中执行一个代码块(里面可以有一个或多个语句),而代码块中最后一个语句的完成值就会成为这个 异步 代码的完成值。

示例​

🌐 Example

并行发送 HTTP 请求

🌐 Issuing HTTP request in parallel

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);
})

将转变为

🌐 will be transformed to

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);
})

安装​

🌐 Installation

npm install --save-dev @babel/plugin-proposal-async-do-expressions

用法​

🌐 Usage

🌐 With a configuration file (Recommended)

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:

🌐 Note: This plugin transpiles async do {} to ES2017 Async arrow function async () => {}. If you target to an older engine, i.e. Node.js 6 or IE 11, please also add @babel/plugin-transform-async-to-generator:

babel.config.json
{
"plugins": [
"@babel/plugin-proposal-async-do-expressions",
"@babel/plugin-transform-async-to-generator"
]
}

通过 CLI​

🌐 Via CLI

Shell
babel --plugins @babel/plugin-proposal-async-do-expressions script.js

通过 Node API​

🌐 Via Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-proposal-async-do-expressions"],
});

参考​

🌐 References