@babel/plugin-proposal-async-do-expressions
async do { .. }
表达式在异步上下文中执行一个块(其中包含一条或多条语句),块内的最终语句完成值成为异步代码的完成值。¥The
async do { .. }
expression executes a block (with one or many statements in it) in an asynchronous context, and the final statement completion value inside the block becomes the completion value of the asynchronous code.
示例
¥Example
并行发送 HTTP 请求
¥Issuing HTTP request in parallel
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
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
- 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
用法
¥Usage
使用配置文件(推荐)
¥With a configuration file (Recommended)
{
"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
:
{
"plugins": [
"@babel/plugin-proposal-async-do-expressions",
"@babel/plugin-transform-async-to-generator"
]
}
通过 CLI
¥Via CLI
babel --plugins @babel/plugin-proposal-async-do-expressions script.js
通过 Node API
¥Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-proposal-async-do-expressions"],
});
参考
¥References