Skip to main content

Editable async-await - intermediate

Async forEach Problem

Switch loop style and see when done logs.

partially simulatedcurated scenariodoes not execute real code
Short answer

The key output order is done -> 1 -> 2. `forEach` starts callbacks and ignores the promises they return.

Real-world bug this helps solve

The UI, test, redirect, or log moves forward before the async result is actually ready. Use `for...of` for sequential work or `Promise.all(items.map(...))` for parallel work.

Common wrong assumption

Expecting `forEach` to behave like `for...of` with await.

Fix direction

Await real dependencies, start independent work together, and choose the loop pattern that matches the behavior you need.

Fixed code pattern
const [user, posts] = await Promise.all([
  fetchUser(),
  fetchPosts()
]);
Visual proof

The console lane proves the visible order: done -> 1 -> 2. The active line and queues show why source order changed.

How to verify in a real app

Measure before and after with logs or test spies: the dependent line should run only after the awaited operation finishes.

Share
Loading editable case...

Related cases

Continue with nearby confusion while the mental model is fresh.

Recommended next

Was this clear?

This stays local for now. It helps you track where the product still needs sharper cases.

Send detail