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

async-generator-functions - 图1info

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

Example

In

JavaScript

  1. async function* agf() {
  2. await 1;
  3. yield 2;
  4. }

Out

JavaScript

  1. var _asyncGenerator = ...
  2. let agf = (() => {
  3. var _ref = _asyncGenerator.wrap(function* () {
  4. yield _asyncGenerator.await(1);
  5. yield 2;
  6. });
  7. return function agf() {
  8. return _ref.apply(this, arguments);
  9. };
  10. })();

For await example

JavaScript

  1. async function f() {
  2. for await (let x of y) {
  3. g(x);
  4. }
  5. }

Example Usage

JavaScript

  1. async function* genAnswers() {
  2. var stream = [Promise.resolve(4), Promise.resolve(9), Promise.resolve(12)];
  3. var total = 0;
  4. for await (let val of stream) {
  5. total += await val;
  6. yield total;
  7. }
  8. }
  9. function forEach(ai, fn) {
  10. return ai.next().then(function(r) {
  11. if (!r.done) {
  12. fn(r);
  13. return forEach(ai, fn);
  14. }
  15. });
  16. }
  17. var output = 0;
  18. forEach(genAnswers(), function(val) {
  19. output += val.value;
  20. }).then(function() {
  21. console.log(output); // 42
  22. });

Try it Out in the REPL

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-async-generator-functions
  1. yarn add --dev @babel/plugin-transform-async-generator-functions
  1. pnpm add --save-dev @babel/plugin-transform-async-generator-functions

Usage

babel.config.json

  1. {
  2. "plugins": ["@babel/plugin-transform-async-generator-functions"]
  3. }

Via CLI

Shell

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

Via Node API

JavaScript

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

References