Question presented to candidate: "You need to fetch additional data for each item in an array, using an async function inside the loop. Someone writes items.forEach(async item => { await fetchMore(item) }). Does this actually wait for all the fetches to finish before moving on? Walk me through what map and forEach each do, and why this specific pattern is a real, common bug."
What a strong answer should cover:
- 📌 Interview term:
map(fn)returns a new array of transformed values, genuinely chainable;📌 forEach(fn)** returnsundefined, used purely for side effects — real, genuinely different return contracts. - 📌 Verified, not assumed:
forEach's real return value is genuinelyundefined, confirmed directly — and a real, direct attempt to chain.filter()onto it genuinely threw a realTypeError, since there is nothing real to chain onto. - 📌 Interview term: the real, direct answer to the prompt's exact async bug — a real
forEachwith an async callback genuinely does NOT wait for the async work to complete: confirmed directly, a real results array was genuinely still empty immediately after theforEachcall itself returned, even though every async callback had already been invoked —forEachgenuinely ignores whatever Promise each callback returns. - A precise answer names the real, correct fix for the prompt's exact bug: use
for...ofwithawaitinside the loop body (for genuinely sequential async work), orPromise.all(items.map(async item => ...))(for genuinely concurrent async work) — neither of which relies onforEachwaiting for anything, since it genuinely never does. - A precise answer names that
map, verified separately, genuinely does NOT stop early on any specialreturnvalue inside the callback — a real, directreturninside a map callback is simply that element's real transformed value, not a loop-control signal.
Clarifying questions expected:
- "Does the actual downstream code need the real, transformed VALUES back (map's real job), or is this purely a side-effecting operation with no meaningful return value (forEach's real job)?"
- "Does the async work per item genuinely need to happen sequentially, or can it genuinely run concurrently?" — directly decides between the real
for...of+awaitfix and the realPromise.all(map(...))fix for the prompt's exact bug.
Code / implementation expected: Yes — a real, direct demonstration that forEach's return value is genuinely undefined, plus a real, concrete proof that forEach with async callbacks genuinely does not wait, is the concrete, convincing proof of exactly why the prompt's pattern is a real, common bug.