A common async/await mistake in JavaScript is passing an async callback to forEach. forEach ignores the promises the callback returns, so the surrounding function carries on and returns before any of the work has finished, and a failure inside the callback becomes an unhandled rejection instead of an error the caller can see. This post is a code review exercise on that bug in a Node bulk import, with the review comment, two fixes and a test.
In production this bug looks like success. A user import is "working" in production. The admin dashboard shows a green checkmark. But the actual table is short a handful of rows. Nobody notices until someone queries the database and a few accounts are just gone. No error in the logs, no failed HTTP response, no alert. The import function returned success, the response was sent to the browser, and then, a few hundred milliseconds later, a few inserts quietly failed because of a duplicate-key constraint. The promises that carried those failures had nobody listening. The function had already left the building.
The root cause was forEach with an async callback. This is a JavaScript code review exercise built around that exact bug: an async/await mistake that passes every linter, every type checker, and most test suites without a whisper. It is a worked example with the full solution, the fix, and the test that catches it. If you review Node.js pull requests, whether the code was written by a colleague or generated by an AI assistant, this is the pattern that will burn you the most quietly, because the keywords async and await are both present, the logic reads sequentially, and nothing about it screams "fire and forget." But that is exactly what it does.
The requirements
An admin needs a bulk import endpoint. The spec is four lines:
- Add an admin endpoint that imports a list of users.
- Every user must be inserted into the database.
- The endpoint must only report success after all inserts have completed.
- A failed insert must not be silently swallowed.
Context: this runs as an admin-triggered batch job. Imports can be several thousand users.
The PR
The AI assistant opened a two-file PR: a new service and a route that wires it up.
src/services/importUsers.js
async function importUsers(users) { users.forEach(async (user) => { await db.insert(user); }); console.log("All users imported ✅"); return { imported: users.length }; } module.exports = { importUsers }; src/routes/admin.js
const express = require("express"); const { listUsers } = require("../services/listUsers"); + const { importUsers } = require("../services/importUsers"); const router = express.Router(); router.get("/users", listUsers); + router.post("/users/import", async (req, res) => { + res.json(await importUsers(req.body.users)); + }); module.exports = router; Nine lines of new service code, three lines of routing. Clean, readable. The PR description says "verified with a small test file, all rows appeared in the table." And they probably did, because with three test users and a local database, every insert finishes before you can blink. The bug only bites at scale, or when one insert is slow, or when one fails.
Try it yourself first. The same PR is in DiffDojo with no spoilers: leave inline comments and a verdict, then come back for the walkthrough. Review this PR. Free, no signup.
Walkthrough: the answer starts here
Where the await is lost: forEach with an async callback
The entire bug lives on line 2 of src/services/importUsers.js:
users.forEach(async (user) => { await db.insert(user); }); Array.prototype.forEach calls its callback once per element, synchronously, in order. It does not look at the return value. It does not know what a Promise is. If you hand it an async function, it calls that function, receives the Promise it returns, and throws it on the floor. The await db.insert(user) on line 3 does pause execution of that particular callback, but nobody is waiting for that callback to finish. forEach is not, importUsers is not, the route handler is not.
So here is what actually happens at runtime. importUsers is called. forEach fires off N async callbacks. Each one starts executing and hits its first await, at which point it yields. forEach returns undefined. Execution continues to line 5: console.log("All users imported ✅"). Line 6: return { imported: users.length }. The route handler gets the result. Express sends a 200 with {"imported": 3000}. The HTTP response is on the wire. The admin sees a green checkmark.
Meanwhile, back in the event loop, those N promises are still resolving. Some inserts have not even started yet. If one of them rejects, say a duplicate key or a connection timeout, that rejection has nowhere to go. There is no .catch() on the promise, no try/catch that wraps the whole batch, no caller awaiting it. In Node.js 15 and later, an unhandled promise rejection terminates the process by default. So a single bad row in a 3,000-user import can crash the server, and the admin already got their success response thirty milliseconds ago.
To be precise about the runtime behavior: Node.js 15+ (released October 2020) changed the default for --unhandled-rejections from warn to throw. On Node 14 and earlier, or if the flag is set to warn, the rejection prints a warning to stderr and keeps running. Either way, the failure is invisible to the caller and breaks requirements 3 and 4.
Which requirements the code breaks
Let's walk through what this code violates:
Requirement 2: "Every user must be inserted into the database." The function returns { imported: users.length } unconditionally. It does not check whether any insert actually succeeded. It returns the count of users it was asked to import, not the count it actually imported. If the database is under load and half the inserts time out, the response still says all of them went through.
Requirement 3: "The endpoint must only report success after all inserts have completed." This is the core failure. The endpoint reports success before the inserts complete. Not after some of them, not after most of them. Before any of them, potentially, because forEach fires off all the callbacks synchronously and then the function falls through to the return statement on the same tick.
Requirement 4: "A failed insert must not be silently swallowed." Every failed insert becomes an unhandled promise rejection. On modern Node, that crashes the process. On older Node, it logs a deprecation warning to stderr that nobody reads. Neither of these surfaces the error to the caller.
The review comment and the verdict
async function importUsers(users) { users.forEach(async (user) => { await db.insert(user); }); Review comment:
forEachignores the promises returned by an async callback. None of these inserts are awaited byimportUsers, so the function returns{ imported: N }and the endpoint responds with 200 before any insert has finished. If an insert fails, the rejection is unhandled. Replace withfor...ofand await each insert, or map to promises andawait Promise.all(...)if order does not matter.
Verdict: Request changes. The endpoint does not wait for the work it claims to have done. This is not a style issue or a nice-to-have. The function literally lies about its own completion. One comment, one blocker, and a clear path to the fix.
The fix: for...of, or Promise.all
The minimal fix is a for...of loop:
- users.forEach(async (user) => { - await db.insert(user); - }); + for (const user of users) { + await db.insert(user); + } This inserts users one at a time, in order, and if any insert throws, the error propagates to the caller. The route handler's await importUsers(...) catches it, Express returns a 500, and the admin knows something went wrong. Requirements 3 and 4 are now met.
If you want parallelism (and your database can handle it), the alternative is:
await Promise.all(users.map((user) => db.insert(user))); Promise.all takes an array of promises, waits for all of them, and rejects if any one rejects. The key difference from the forEach version: someone is actually holding the promises. Promise.all collects them, await suspends importUsers until they all settle, and a failure propagates upward.
For a several-thousand-user import, you might worry about firing 3,000 concurrent database inserts. That is a reasonable concern, and if you hit it, the answer is batching (chunking the array and processing each chunk with Promise.all). But that is an optimization discussion for the next round of review, not a reason to keep the current code that does not wait at all.
A test that catches the old code and passes the fix
The trick is making the insert take a measurable amount of time so you can observe whether the function actually waits:
const { importUsers } = require("../services/importUsers"); test("importUsers waits for all inserts", async () => { const inserted = []; db.insert = (user) => new Promise((resolve) => setTimeout(() => { inserted.push(user); resolve(); }, 50) ); await importUsers([{ name: "a" }, { name: "b" }]); expect(inserted).toEqual([{ name: "a" }, { name: "b" }]); }); test("importUsers surfaces a failed insert", async () => { db.insert = () => Promise.reject(new Error("duplicate key")); await expect(importUsers([{ name: "x" }])).rejects.toThrow("duplicate key"); }); The first test stubs db.insert with a 50ms delay. With the forEach version, importUsers returns immediately, await resolves, and inserted is still empty. The assertion fails. With the for...of fix, the function waits for both inserts, and the array contains both users.
The second test checks requirement 4. With forEach, the rejection becomes unhandled. With for...of, it propagates and the test passes.
The same missing await in real projects, including a security advisory
None of this is obscure. MDN's page for forEach states that it "expects a synchronous function" and "does not wait for promises." It still gets past experienced teams. In 2021 a VS Code maintainer opened an issue listing forEach(async ...) calls in the file explorer that were never awaited, with the note that "forEach with async will execute all promises inside in parallel but return immediately." The author of that code replied that it looked like an oversight and fixed it.
A dropped await becomes a security bug when the promise was a permission check. In March 2026 StudioCMS published a high-severity advisory (CVE-2026-32101): an async isAuthorized() was called without await, and because "a Promise object is always truthy in JavaScript," the branch that should have returned a 401 never ran. Any user with the lowest role could upload, delete and rename files in the storage bucket. The fix was the keyword await in two places. We took a closer look at that bug class in a separate post.
If the project uses TypeScript, the typescript-eslint rule no-misused-promises reports an async callback passed to forEach; its documentation shows exactly that call as an example of incorrect code. This PR is plain JavaScript, so the reviewer is the check.
The review habit: ask who awaits the promise
Every time you see an async callback passed to a higher-order function, ask one question: who awaits the promise this callback returns? For for...of, it is the loop. For Promise.all(arr.map(async ...), it is Promise.all. For forEach, filter, reduce, map (without wrapping in Promise.all), and most event-handler registrations, the answer is nobody. That single question would have caught the bug in this exercise, and it catches the same bug in migration scripts, webhook dispatchers, queue consumers, and every other place where someone writes .forEach(async and moves on because the keywords look right.
Common questions
Can you show a JavaScript code review exercise about async and await mistakes?
Yes, this post is one. The pull request adds a bulk import that loops with users.forEach(async (user) => { await db.insert(user); }), so the function returns its success count before any insert has completed and a failed insert is never reported. The review comment, the verdict (request changes), the for...of and Promise.all fixes and two tests are above. The same PR is open in DiffDojo without signup if you want to review it before reading the answer.
Why does await not work inside forEach?
forEach calls the callback for each element and discards whatever it returns. An async callback returns a promise, so each await pauses only that callback, while forEach itself finishes immediately and the outer function moves on. Use for...of when the steps must run in order, or await Promise.all(items.map(async ...)) when they can run in parallel.
How do I spot a missing await in a pull request?
For every async call, ask who holds the promise it returns. A call with no await, no return and no Promise.all around it is fire and forget. The same question applies to async callbacks handed to forEach, to event emitters and to any function that ignores return values. Then look at what the function reports: if it returns success, find the line that proves the work finished first.
Where can I practice catching async bugs in code review?
DiffDojo has this PR and other Node and React pull requests with planted async bugs such as un-awaited promises and out-of-order responses, plus clean ones where the right call is to approve. You leave inline comments, give a verdict and get graded against a canonical review. One PR in every stack is open without signup, a free account opens one more of your choice, and the pass opens the rest of the library.
Related walkthroughs: a React race condition in a search box, a hallucinated Lodash method, pagination that drops the last records.
Originally published on DiffDojo. DiffDojo is a trainer for reviewing AI-written pull requests: pick a PR and review it cold. One PR in every stack is free, no signup; a free account unlocks one more, and the pass opens the whole library.

