Web Development Bug Report

forEach with an async callback reported success before any email was sent

A Node.js job marked a batch of reminder emails as sent and exited, while most sends were still in flight or had failed. The cause was forEach with an async callback. How we proved it, and when to use for...of, Promise.all, allSettled or a concurrency limit.

Julian Navarro Julian Navarro @juliannavarro · November 16, 2026 · 7 min read · 80 Views
Banner: async callbacks inside forEach not being awaited

Every morning a scheduled Node.js job sends payment reminder emails to customers with an invoice due in three days. It runs as a Kubernetes CronJob, logs a summary, and exits. One Monday the summary said:

2026-10-19T06:00:04.112Z reminders: batch complete sent=1843 failed=0 duration_ms=212

Two hundred milliseconds for 1,843 emails would be impressive. The email provider's dashboard told a different story: 312 messages accepted that morning. Customers called support about late fees on invoices they had never been reminded about.

The job's main loop:

async function run() {
  const invoices = await db.invoicesDueIn(3);
  let sent = 0;
  let failed = 0;

  invoices.forEach(async (invoice) => {
    try {
      await mailer.send(reminderFor(invoice));
      await db.markReminded(invoice.id);
      sent++;
    } catch (err) {
      failed++;
      log.error({ err, invoiceId: invoice.id }, "reminder failed");
    }
  });

  log.info({ sent: invoices.length, failed, duration_ms: elapsed() }, "batch complete");
  process.exit(0);
}

Two things stood out once we read it carefully. The summary logged invoices.length as sent, not the sent counter. And process.exit(0) ran right after the forEach, while the sends it started were still waiting on the network.

Proving it

We ran the job locally against a fake mailer that takes 100 ms per send and prints when it finishes:

06:00:00.010 batch complete sent=5 failed=0
06:00:00.011 process exiting

No "sent" lines at all. Without the process.exit, the output changed to:

06:00:00.010 batch complete sent=5 failed=0
06:00:00.112 mail sent to invoice 1
06:00:00.113 mail sent to invoice 2
...

The summary is printed first, then the work happens. In production, the sends that managed to complete before process.exit(0) were the 312 the provider saw. The rest were cut off mid-request.

What forEach does with an async callback

Array.prototype.forEach calls the callback once per element and ignores its return value. An async function always returns a promise. So forEach starts each callback, gets a promise back, throws the promise away, and moves to the next element. When forEach returns, every callback has started and run up to its first await, and none has finished.

The await inside the callback only pauses that callback. It does not pause forEach, and it does not pause run(). There is nothing in run() that waits for the callbacks, so execution continues straight to the summary and the exit.

The same is true of map, filter and reduce with async callbacks, with one difference: map returns the array of promises, so you can wait for them. forEach returns undefined, so there is nothing to wait for.

Why errors disappeared

Each callback had its own try/catch, so failures would have been counted in failed, but only after the summary had already been logged with failed=0. Without that try/catch, the rejections would have been unhandled, and since Node.js 15 an unhandled rejection crashes the process by default. That would at least have been visible. The well-meaning error handling made the bug quieter.

Environment

Item Value
Runtime Node.js 22 LTS
Job Kubernetes CronJob, single pod
Batch size about 2,000 invoices on a typical day
Mail provider HTTP API, rate limit 50 requests per second per key

The right fix depends on whether the work should run one at a time, all at once, or somewhere in between.

Option 1: sequential with for...of

for...of works with await because the loop body runs inside the async function itself:

for (const invoice of invoices) {
  try {
    await mailer.send(reminderFor(invoice));
    await db.markReminded(invoice.id);
    sent++;
  } catch (err) {
    failed++;
    log.error({ err, invoiceId: invoice.id }, "reminder failed");
  }
}

Correct and simple. For 2,000 emails at about 150 ms each, though, it takes five minutes. Acceptable for this job, but not for larger batches.

Option 2: all at once with Promise.all or Promise.allSettled

const results = await Promise.allSettled(
  invoices.map(async (invoice) => {
    await mailer.send(reminderFor(invoice));
    await db.markReminded(invoice.id);
  }),
);
const failed = results.filter((r) => r.status === "rejected");

Promise.all rejects as soon as one promise rejects, and the others keep running with nobody waiting for them. For a batch where each item is independent, Promise.allSettled is usually what you want: it waits for every promise and tells you which succeeded.

The problem here is the rate limit. Starting 2,000 HTTP requests at once got most of them rejected with 429 Too Many Requests.

Option 3: bounded concurrency

What we shipped runs at most N sends at a time. A small worker-pool helper, no dependency needed:

async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;

  async function worker() {
    while (next < items.length) {
      const i = next++;
      try {
        results[i] = { status: "fulfilled", value: await fn(items[i], i) };
      } catch (reason) {
        results[i] = { status: "rejected", reason };
      }
    }
  }

  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
  return results;
}

next++ is safe without a lock because JavaScript runs one piece of code at a time on the event loop; two workers cannot both read next before either increments it.

The job now reads:

async function run() {
  const invoices = await db.invoicesDueIn(3);
  const results = await mapLimit(invoices, 20, async (invoice) => {
    await mailer.send(reminderFor(invoice));
    await db.markReminded(invoice.id);
  });

  const failed = results.filter((r) => r.status === "rejected");
  for (const f of failed) log.error({ err: f.reason }, "reminder failed");
  log.info({ sent: results.length - failed.length, failed: failed.length,
             duration_ms: elapsed() }, "batch complete");

  process.exitCode = failed.length > 0 ? 1 : 0;
}

With a limit of 20 and about 150 ms per send, 2,000 emails take around 15 seconds and stay well under the provider's limit.

Removing process.exit

We replaced process.exit(0) with process.exitCode. Node.js exits on its own when there is nothing left on the event loop, after pending work is done. Setting exitCode reports success or failure to Kubernetes without cutting off anything still running. If the process does not exit, that is a real bug (an open handle) worth finding, not something to paper over.

1. A test that checks the summary waits for the work. The fake mailer resolves after a delay and counts calls:

import { test } from "node:test";
import assert from "node:assert/strict";

test("run waits for every send before reporting", async () => {
  const mailer = fakeMailer({ delayMs: 20, failFor: ["inv-3"] });
  const log = captureLog();
  await run({ db: fakeDb(["inv-1", "inv-2", "inv-3"]), mailer, log });

  assert.equal(mailer.calls, 3);
  assert.deepEqual(log.last("batch complete"), { sent: 2, failed: 1, ...log.anyDuration });
});

On the old code the assertion on mailer.calls failed with 0, because the test finished first.

2. Lint rule. ESLint's no-await-in-loop is the opposite of what we want here, so we left it off. The useful rule is @typescript-eslint/no-misused-promises, which reports a promise-returning function passed where a void callback is expected, exactly the forEach(async ...) shape. We also enabled @typescript-eslint/no-floating-promises for promises that are created and never awaited.

src/jobs/reminders.ts:14:20  error  Promise returned in function argument where a void return was expected  @typescript-eslint/no-misused-promises

3. Production. The next run logged sent=1871 failed=4 duration_ms=14820, and the provider dashboard showed 1,871 accepted messages. The four failures were invalid addresses, now visible and retried the next day.

4. Reconciliation and security. We re-sent reminders for the invoices that were missed and waived the late fees caused by the bug. A silent partial run like this is also an audit problem for anything legally required (payment notices, security alerts), so the job now writes one row per invoice to a delivery log and an alert fires if the job reports fewer sends than invoices.

Takeaways

  • forEach ignores the promise an async callback returns. Nothing waits for the work.
  • Use for...of for sequential work, Promise.allSettled for independent parallel work, and a concurrency limit when a downstream service has rate limits.
  • Do not call process.exit() in a job with pending I/O; set process.exitCode instead.
  • Enable no-misused-promises and no-floating-promises to catch this before review.

References: Array.prototype.forEach on MDN, Promise.allSettled on MDN, Node.js process.exitCode, typescript-eslint no-misused-promises.

Add a label

#javascript #nodejs #concurrency #promises #async-await
Written by
Julian Navarro @juliannavarro

I have worked as a backend engineer for about twelve years, mostly in Python and Go, with enough JavaScript on the side to keep the frontend team honest. Most of that time was spent on internal platforms: billing jobs, import pipelines and the services everything else quietly depends on. What I keep seeing is that the expensive bugs rarely come from exotic corners. They come from fundamentals we all learned once and then stopped thinking about: a copy that was not deep, a loop that turned quadratic at real volume, an async call nobody awaited, a subclass that broke a rule its parent relied on. Each post here starts from one of those failures, shows how we traced it, the smallest fix that held and the test that keeps it from coming back. Where a principle or pattern helps, I show it on real code, and I am just as clear about where it only adds weight.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.