Skip to content

Why `await` inside a loop is slow: the event loop and microtasks

A for loop with await runs your async work one item at a time. Here is what the event loop and the microtask queue are doing, and three ways to fix it, with timings from a real run.

By StackNothingNode.js 22.236 min read

Why `await` inside a loop is slow: the event loop and microtasks: article title on a blue background

You have a list of ten IDs and an async function that loads one item. You write the obvious loop, ship it, and the page takes ten times longer than the slowest single request. Nothing is broken. The code does exactly what it says: it waits for each item before it starts the next.

This article shows why, what the event loop is doing while you wait, and how to run the work concurrently without flooding whatever is on the other end.

The slow version

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const fetchItem = async (id) => {
  await sleep(100); // stands in for a network or disk call
  return id * 2;
};
const ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 
const results = [];
for (const id of ids) {
  results.push(await fetchItem(id));
}

await suspends the surrounding async function until the promise settles. In a loop, that means the next iteration can't begin until the previous one is done. Ten calls of 100 ms each are ten sequential waits.

I ran this on Node.js 22.23.5, with sleep(100) standing in for real I/O:

10 items, sequential await

1003 msto100 ms

Lab, Node.js 22.23.5 on a GitHub Actions runner, 2026-12-01. Each item is a simulated 100 ms timer, not a real network call. 'After' is the Promise.all version below. Single run, not averaged.

The simulated timers make the arithmetic clean, but the same shape holds for real I/O: sequential total is roughly the sum of the waits, concurrent total is roughly the longest one.

What the event loop does while you wait

JavaScript runs your code on one thread. When an await hits a promise that isn't settled yet, the function is suspended and the thread is free to do other things. Nothing blocks. The loop is slow only because your own code never started the second call.

Two queues matter here:

  • Macrotasks (timers, I/O callbacks, and similar). The loop takes one, runs it to completion, and then...
  • Microtasks (promise reactions, queueMicrotask). After the current task finishes and the call stack is empty, the whole microtask queue is drained before the loop moves on.

A continuation after await is a microtask once the awaited promise settles. This script makes the order visible:

console.log("1 sync start");
setTimeout(() => console.log("5 timeout (macrotask)"), 0);
Promise.resolve().then(() => console.log("3 microtask: then"));
queueMicrotask(() => console.log("4 microtask: queueMicrotask"));
(async () => {
  console.log("2 sync inside async fn");
  await null;
  console.log("4b continuation after await (microtask)");
})();
console.log("2b sync end");

Output from the run:

1 sync start
2 sync inside async fn
2b sync end
3 microtask: then
4 microtask: queueMicrotask
4b continuation after await (microtask)
5 timeout (macrotask)

The async function runs synchronously up to its first await. Everything after it waits for a microtask turn, and the setTimeout callback, even with a delay of 0, comes after all of them.

Fix 1: start everything, then wait once

If the items don't depend on each other, create all the promises first and await them together:

const results = await Promise.all(ids.map(fetchItem));

ids.map(fetchItem) calls the function for every ID immediately; each call runs up to its first await and returns a pending promise. Promise.all then resolves with the values in input order, no matter which finishes first. In the run above it took 100 ms for the ten items, with the same results (2,4,6,...,20).

With allSettled, each entry is { status, value } or { status, reason }. I made the item with ID 2 throw and mapped the three results to their statuses; the run printed fulfilled,rejected,fulfilled and the reason job 2 failed.

const settled = await Promise.allSettled(ids.map(fetchItem));
const failed = settled.filter((r) => r.status === "rejected");

Fix 2: cap the concurrency

Firing 10,000 requests at once is its own bug: you can exhaust sockets, hit rate limits, or overload a database. A small worker pool keeps a fixed number in flight:

async function mapLimit(items, limit, fn) {
  const out = new Array(items.length);
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next++;
      out[i] = await fn(items[i]);
    }
  }
  const workers = Array.from({ length: Math.min(limit, items.length) }, worker);
  await Promise.all(workers);
  return out;
}
 
const results = await mapLimit(ids, 3, fetchItem);

Each worker pulls the next index, awaits it, and repeats. Because JavaScript is single-threaded, next++ can't race with another worker: there is no await between reading next and incrementing it. Results are written by index, so order is preserved.

With the same ten simulated 100 ms items and a limit of 3, the run took 400 ms: four rounds of up to three at a time (3 + 3 + 3 + 1). That is the trade you tune: more concurrency finishes sooner, less is gentler on the other side.

When the sequential loop is correct

Sequential await is not a mistake in itself. Keep it when:

  • Order matters. Each step needs the result of the previous one (a pagination cursor, a migration that must run in sequence).
  • Side effects must not overlap. Writing to the same file or resource, or an API that requires one request at a time.
  • You want to stop early. A for...of with await can break as soon as you have what you need; Promise.all has already started everything.

Note also that array.forEach(async (x) => { await ... }) does not wait at all: forEach ignores the returned promises, so the code after it runs before the work is done. Use for...of for sequential or Promise.all(array.map(...)) for concurrent.

The other trap: starving the event loop

Concurrency from Promise.all is I/O concurrency. It doesn't run your JavaScript on multiple threads. And because the microtask queue is drained completely before the loop moves on, microtasks that keep scheduling more microtasks can hold everything else back:

let n = 0;
const t = performance.now();
setTimeout(
  () => console.log("timer fired after", Math.round(performance.now() - t), "ms (asked for 0)"),
  0,
);
function spin() {
  if (++n < 5_000_000) queueMicrotask(spin);
}
spin();

On the same Node.js 22.23.5 runner the output was:

timer fired after 647 ms (asked for 0)

The timer was ready almost immediately, but it had to wait for five million chained microtasks. In a browser, the same pattern delays rendering and input handling. If you have a long pile of CPU work, split it into chunks and yield to the event loop between them (for example with setTimeout) or move it to a worker.

A checklist

  • Independent items: Promise.all(items.map(fn)).
  • Need every result, even failures: Promise.allSettled.
  • Large or rate-limited lists: a bounded pool such as mapLimit.
  • Dependent or order-sensitive steps: a plain for...of with await.
  • Never await inside forEach.

Sources

Docs & Tooling

Welcome to the StackNothing blog

What this blog covers, who it's for, and how each article is put together: deep dives into languages and frameworks, case studies and performance write-ups.

By StackNothing 2 min read