swc icon indicating copy to clipboard operation
swc copied to clipboard

for await... does not unwrap promises

Open public opened this issue 3 years ago • 1 comments

Describe the bug

When y is a sync iterable of Promisesfor await (const x of y)... should unwrap the promises results into x.

This works correctly in Node 16 with https://github.com/microsoft/TypeScript but SWC produces code that does not unwrap the promises.

Input code

const a1 = [1, 2, 3];
const a2 = a1.map((x) => Promise.resolve(x));

async function f() {
  for await (const v of a2) {
    console.log(v);
  }
}

f();

Config

{
  "compilerOptions": {
    "outDir": "./built",
    "allowJs": true,
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "lib": ["dom", "esnext"],
    "strict": true,
    "jsx": "preserve"
  },
  "include": ["src/**/*", "libraries/**/*"],
  "exclude": ["src/**/*.spec.*", "src/**/*.test.*"],
  "ts-node": {
    "swc": true
  }
}

Playground link

https://play.swc.rs/?version=1.2.222&code=H4sIAAAAAAAAAyXMwQoCIRSF4f19irNUGASnpUzP0D5aiGgIjjfUrIh59wy33%2BH8jnNtsBobrnrBuuB0M%2BSmrkOtVrt9CPGW2M64FN5j9ar4yqn7odIQ2frJDuGZXYucEYTEl4DABfZlY4OYwQ4OozpX4I%2BcvEp8F310gIMOonE39APe40qjmAAAAA%3D%3D&config=H4sIAAAAAAAAAy2MSw6AIAxE7zJrt7rgNg1WgxEkbU0khLsLxt3Mm0%2FFoR6uIpMoy1BaktEDByuZ1UvIhjbBSHa2jllnTIghha2Mvr9iFlaF2%2BhU7hGl%2FeTftj6N13oPUL%2FL72JBay9cWA1%2BfAAAAA%3D%3D

Expected behavior

It prints

1
2
3

Actual behavior

It prints

Promise { 1 }
Promise { 2 }
Promise { 3 }

Version

1.2.223

Additional context

No response

public avatar Aug 03 '22 13:08 public

I think this is mostly a result of me using the es5 target when I don't really need to so I am going to change my tsconfig to include "extends": "@tsconfig/node16/tsconfig.json" which generates code that defers all the async iteration magic to Node.

public avatar Aug 03 '22 13:08 public

This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

swc-bot avatar Oct 16 '22 00:10 swc-bot