Skip to content

Per-iteration scoped variables not emitted per-iteration when using for..await #42001

Description

@rbuckton

I found a similar case: constants with scope inside a for await are compiled outside __generator and so are shared across iterations.

const sleep = (tm: number) => new Promise(resolve => setTimeout(resolve, tm));

async function* gen() {
    yield 1;
    await sleep(1000);
    yield 2;
}

const log = console.log;

(async () => {
    for await (const outer of gen()) {
        log(`I'm loop ${outer}`);
        (async () => {
            const inner = outer;
            await sleep(2000);
            if (inner === outer) {
                log(`I'm loop ${inner} and I know I'm loop ${outer}`);
            } else {
                log(`I'm loop ${inner}, but I think I'm loop ${outer}`);
            }
        })();
    }
})();

Using es5 target, it prints:

[LOG]: I'm loop 1 
[LOG]: I'm loop 2 
[LOG]: I'm loop 1, but I think I'm loop 2 
[LOG]: I'm loop 2 and I know I'm loop 2 

Using ES2015 or following, it prints (as expected):

[LOG]: I'm loop 1 
[LOG]: I'm loop 2 
[LOG]: I'm loop 1 and I know I'm loop 1 
[LOG]: I'm loop 2 and I know I'm loop 2 

I was able to replicate it on the playground with version 4.0.1 and older 3.x.x versions.

Originally posted by Angelo Di Pilla (@dippi) in #40047 (comment)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issueRescheduledThis issue was previously scheduled to an earlier milestone

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions