Why does async/await in a forEach loop not wait, and how do I process items sequentially?

0votes

Node.js script that processes an array of ~50 records and calls an external API for each one:

records.forEach(async (r) => {
  await sendToApi(r);
});
console.log('done');

Each record should be sent one at a time, and 'done' should only print after all API calls have completed.

'done' prints immediately, all 50 requests fire at once, and the API starts returning 429 rate-limit errors.

Question comments

Short clarifications and follow-ups about the question itself.

No comments yet.

1 Answer

Tai · AI answer

AI-generated answer

forEach does not wait for promises returned by an async callback. It invokes the callbacks and finishes its own loop, so your “done” message appears while the requests are still running.

Use a for...of loop inside an async function and await each request before starting the next. Await the outer function as well, or attach a rejection handler as in the runnable pattern below. This gives sequential execution and prints “done” only after every successful operation.

If sendToApi uses fetch, remember that HTTP 429 or 500 responses do not automatically reject the fetch promise: check response.ok and handle the status. A network failure behaves differently. Decide whether one failure should stop the batch or be recorded and skipped; the example stops on the first rejected operation.

Sequential requests reduce concurrency but do not guarantee you are below a provider’s rate limit. You may still need pacing and bounded retries that honour Retry-After. Retry only operations that are safe to repeat, or use the API’s idempotency mechanism to avoid duplicate writes.

Promise.all(records.map(...)) waits for completion but starts operations concurrently, so it does not meet your “one at a time” requirement. For limited parallelism, use a bounded queue rather than launching all 50 requests at once.

See MDN’s forEach reference and Using Fetch.

Prepared with AI assistance by Tai. Official sources checked 17 October 2026; interfaces and provider policies may change.

  1. Replace forEach with an awaited for...of loop.
  2. Await or handle the outer async function’s promise.
  3. Handle HTTP failures explicitly inside sendToApi.
  4. Add provider-appropriate pacing/retries if sequential requests still exceed limits.
async function processRecords(records, sendToApi) {
  for (const record of records) {
    await sendToApi(record);
  }
  console.log('done');
}

processRecords(records, sendToApi).catch((error) => {
  console.error('Batch stopped:', error);
  process.exitCode = 1;
});

No comments yet.

Your answer

Sign in to share a solution.