Skip to content

async: per-iteration let/const binding collapses for closures created in a loop body (every closure sees the last value) #6345

Description

@proggeramlug

Summary

Inside an async function, a let/const declared in a loop body and captured by a closure loses its per-iteration binding: every closure sees the last iteration's value. The same code in a non-async function is correct.

Silent wrong answer — no throw, exit 0.

Repro

async function main() {
  const fns: (() => void)[] = [];
  for (let i = 0; i < 9; i++) {
    const j = i;
    fns.push(() => console.log("j =", j));
  }
  fns.forEach((f) => f());
  await 0;
}
main();
output
node 26 j = 0, j = 1, … j = 8
perry main j = 8 × 9

Capturing the loop variable directly (fns.push(() => console.log(i))) is equally affected — node prints 0..8 (per-iteration let binding), perry prints 9 nine times (the single shared cell, read after the loop has exited).

Notes

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions