Skip to main content

@babel/plugin-transform-async-generator-functions

信息

此插件包含在 @babel/preset-env 中,在 ES2018

¥This plugin is included in @babel/preset-env, in ES2018

示例

¥Example

输入

¥In

JavaScript
async function* agf() {
await 1;
yield 2;
}

输出

¥Out

JavaScript
var _asyncGenerator = ...

let agf = (() => {
var _ref = _asyncGenerator.wrap(function* () {
yield _asyncGenerator.await(1);
yield 2;
});

return function agf() {
return _ref.apply(this, arguments);
};
})();

以 await 为例

¥For await example

JavaScript
async function f() {
for await (let x of y) {
g(x);
}
}

用法示例

¥Example Usage

JavaScript
async function* genAnswers() {
var stream = [Promise.resolve(4), Promise.resolve(9), Promise.resolve(12)];
var total = 0;
for await (let val of stream) {
total += await val;
yield total;
}
}

function forEach(ai, fn) {
return ai.next().then(function(r) {
if (!r.done) {
fn(r);
return forEach(ai, fn);
}
});
}

var output = 0;
forEach(genAnswers(), function(val) {
output += val.value;
}).then(function() {
console.log(output); // 42
});

在 REPL 中试用

¥Try it Out in the REPL

安装

¥Installation

npm install --save-dev @babel/plugin-transform-async-generator-functions

用法

¥Usage

¥With a configuration file (Recommended)

babel.config.json
{
"plugins": ["@babel/plugin-transform-async-generator-functions"]
}

通过 CLI

¥Via CLI

Shell
babel --plugins @babel/plugin-transform-async-generator-functions script.js

通过 Node API

¥Via Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-async-generator-functions"],
});

参考

¥References