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.
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);
})
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
{
"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:
{
"plugins": [
"@babel/plugin-proposal-async-do-expressions",
"@babel/plugin-transform-async-to-generator"
]
}
babel --plugins @babel/plugin-proposal-async-do-expressions script.js
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-proposal-async-do-expressions"],
});
© 2014-present Sebastian McKenzie
Licensed under the MIT License.
https://babeljs.io/docs/babel-plugin-proposal-async-do-expressions/