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 @dippi in #40047 (comment)
I found a similar case: constants with scope inside a
for awaitare compiled outside__generatorand so are shared across iterations.Using es5 target, it prints:
Using ES2015 or following, it prints (as expected):
I was able to replicate it on the playground with version
4.0.1and older3.x.xversions.Originally posted by @dippi in #40047 (comment)