Back|
backendAsync/Await in forEach
mediumbug3m

Async/Await in forEach

0:00

A developer is trying to process an array of user IDs, fetching data for each one sequentially. They're confused why all the fetches seem to happen at once, and the function returns before the data is processed.

0 flagged
javascriptclick lines to flag bugs
1
async function processUsers(userIds) {
2
  const results = [];
3
 
4
  userIds.forEach(async (id) => {
5
    const user = await fetchUser(id);
6
    const processed = await processData(user);
7
    results.push(processed);
8
  });
9
 
10
  console.log('All done!', results);
11
  return results; // Returns empty array!
12
}
13
 
14
// Helper functions (assume these work correctly)
15
async function fetchUser(id) {
16
  return { id, name: `User ${id}` };
17
}
18
 
19
async function processData(user) {
20
  return { ...user, processed: true };
21
}