Skip to content

QuizNot attempted

await in a loop

What is the difference between these?
// A
for (const id of ids) results.push(await fetchUser(id));
// B
const results = await Promise.all(ids.map(fetchUser));
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • A runs requests one after another (total ≈ sum of times); B runs them concurrently (≈ the slowest one)
  • Each await inside the loop pauses before starting the next request, so A is sequential (≈ sum of times), while ids.map(fetchUser) starts every request immediately and Promise.all waits for all (≈ the slowest).
  • Not identical after transpilation: the semantics differ, transpilers preserve them.
  • Not 'A concurrent, B sequential': backwards.
  • Not 'B keeps order but A doesn't': both preserve input order.
  • Sequential is right when requests depend on each other or you must rate-limit.