HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptMajorpending

Gotcha: JavaScript async/await error handling in loops

Submitted by: @anonymous··
0
Viewed 0 times
async loopforeach asyncpromise.allparallel awaitcontrolled concurrency

Error Messages

unhandled promise rejection in loop
forEach async not awaiting

Problem

Using async/await in loops can cause unexpected behavior: sequential instead of parallel, unhandled rejections, or lost errors.

Solution

Async loop patterns and pitfalls:

const urls = ['url1', 'url2', 'url3'];

// SEQUENTIAL: await in for...of (slow but ordered)
for (const url of urls) {
  const data = await fetch(url);  // One at a time
  process(data);
}

// PARALLEL: Promise.all (fast, all or nothing)
const results = await Promise.all(
  urls.map(url => fetch(url))
);  // All run concurrently

// PARALLEL WITH ERROR HANDLING: Promise.allSettled
const results = await Promise.allSettled(
  urls.map(url => fetch(url))
);
results.forEach((result, i) => {
  if (result.status === 'fulfilled') {
    process(result.value);
  } else {
    console.error(`Failed ${urls[i]}: ${result.reason}`);
  }
});

// BAD: forEach doesn't await!
urls.forEach(async (url) => {
  const data = await fetch(url);  // Fire and forget!
  process(data);  // May run after the loop continues
});
// Code here runs BEFORE any fetches complete!

// BAD: map without Promise.all
urls.map(async (url) => {
  await fetch(url);
});  // Returns array of promises, nobody awaits them!

// CONTROLLED CONCURRENCY: Process N at a time
async function mapWithConcurrency(items, fn, concurrency = 5) {
  const results = [];
  for (let i = 0; i < items.length; i += concurrency) {
    const batch = items.slice(i, i + concurrency);
    const batchResults = await Promise.all(batch.map(fn));
    results.push(...batchResults);
  }
  return results;
}

await mapWithConcurrency(urls, fetch, 3);  // 3 at a time

// REDUCE with async (sequential processing)
const total = await urls.reduce(async (accPromise, url) => {
  const acc = await accPromise;
  const data = await fetch(url);
  return acc + data.length;
}, Promise.resolve(0));

Why

forEach and map don't understand async functions - they don't await the returned promises. for...of works but is sequential. Promise.all is parallel but fails fast on first error.

Context

JavaScript async programming patterns

Revisions (0)

No revisions yet.