rpetrich / babel-plugin-transform-async-to-promises

Transform async/await to somewhat idiomatic JavaScript promise chains
MIT License
246 stars 17 forks source link

Support for `yield*` in async generators #80

Open ROpdebee opened 2 years ago

ROpdebee commented 2 years ago

Example:

async function* test() {
    yield* [1, 2, 3];
}

async function test2() {
    for await (const x of test()) {
        console.log(x);
    }
}

test2();

Expected result: The async generator should yield 3 numbers, and the code above should log to the console thrice, once for each item in the array.

Actual result: The async generator yields once, with the full array. The code only logs once, and logs the full array.

It seems yield* is handled as a normal yield instead of yielding each element from the iterable separately.

Transformed output:

  const test2 = _async_1(function () {
    return _continueIgnored_1(_forAwaitOf_1(test(), function (x) {
      console.log(x);
    }));
  });

  const test = function test() {
    return new _AsyncGenerator_1(function (_generator) {
      return _generator._yield([1, 2, 3]).then(_empty_1);
    });
  };

  test2();

babel 7.16.7 babel-plugin-transform-async-to-promises 0.8.18

Babel config:

module.exports = {
    presets: [
        ['@babel/preset-typescript', {
            isTSX: true,
            allExtensions: true,
        }],
        ['@babel/preset-env', {
            corejs: '3.19',
            useBuiltIns: 'entry',
            exclude: [
                '@babel/plugin-transform-async-to-generator',
                '@babel/plugin-proposal-async-generator-functions',
            ],
        }],
    ],
    plugins: [
        '@babel/plugin-syntax-jsx',
        ['babel-plugin-transform-async-to-promises', {
            externalHelpers: true,
        }],
        ['@babel/plugin-transform-runtime', {
            regenerator: true,
            helpers: false,
        }],
    ],
    sourceType: 'unambiguous',
    comments: false,
};