πŸ”΄ HardAsync BugsπŸ› Debug Challenge

Async function in forEach

Buggy Code β€” Can you spot the issue?

async function saveAllUsers(users) {
  users.forEach(async (user) => {
    await saveUser(user);
    console.log(`Saved ${user.name}`);
  });
  console.log('All saved!');
}

Fixed Code

async function saveAllUsers(users) {
  // Option 1: Sequential (one at a time)
  for (const user of users) {
    await saveUser(user);
    console.log(`Saved ${user.name}`);
  }

  // Option 2: Parallel (all at once, faster)
  // await Promise.all(users.map(user => saveUser(user)));

  console.log('All saved!');
}

Bug Explained

Bug: forEach doesn't await async callbacks. It fires all async functions and immediately moves on. "All saved!" logs before any save completes.

Explanation: forEach ignores the Promise returned by async callbacks. Use for...of with await for sequential, or Promise.all(array.map(...)) for parallel.

Key Insight: forEach + async = fire and forget. Use for...of or Promise.all(map()) when you need to await async operations on arrays.

More Async Bugs Debug Challenges

🟒 EasyMissing await causes wrong resultβ†’πŸŸ‘ MediumSequential awaits killing performanceβ†’πŸŸ‘ MediumSwallowed error in async functionβ†’πŸ”΄ HardRace condition in state updateβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab