跳到主要内容

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

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

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

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

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"
]
}

Via CLI

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

Via Node API

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

References