跳至主要内容

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

信息

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

示例

输入

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

输出

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 示例

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

示例用法

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 中试用

安装

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

用法

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

通过 CLI

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

通过 Node API

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

参考