← Tous les articles

JavaScript: await in a loop, why it is slow and what to do

A for loop with await takes ten seconds to load ten items? Requests go one by one. Promise.all and a concurrency limit fix it.

JavaScript: await in a loop, why it is slow and what to do

Key points

  • await inside a for loop runs requests one after another.
  • Promise.all runs them in parallel.
  • For many requests, cap concurrency so you do not flood the API.

A dashboard that loads stats for twenty projects takes several seconds to appear. The code is simple: a loop and an await. That is exactly the problem.

The problem: requests in single file

const results = [];
for (const id of ids) {
  results.push(await fetchStats(id)); // waits for each response
}

At 300 ms per request, twenty requests take 6 seconds, even though they are independent and could all start at once.

The fix: Promise.all

const results = await Promise.all(ids.map(id => fetchStats(id)));

All requests start together; total time becomes that of the slowest. Results keep the order of ids.

Handling failures

Promise.all rejects as soon as one request fails. To show what did work:

const settled = await Promise.allSettled(ids.map(fetchStats));
const ok = settled.filter(r => r.status === 'fulfilled').map(r => r.value);

Capping concurrency

Firing 500 requests at once can hit API rate limits (429) or overload the server. Work in batches:

async function inBatches(items, size, fn) {
  const out = [];
  for (let i = 0; i < items.length; i += size) {
    out.push(...await Promise.all(items.slice(i, i + size).map(fn)));
  }
  return out;
}
const stats = await inBatches(ids, 5, fetchStats);

A sequential loop is still right when each step depends on the previous one, or when write order matters.

FAQ

Does forEach with async work?

No: forEach does not wait for promises, so code after the loop runs before the requests finish.

What about Node.js on the server?

Same principle, same care with the database: a connection pool already caps concurrency.

Facing this on your site or app? We diagnose and fix it.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →