1. Home
  2. Interview Questions
  3. JavaScript
  4. Why is using await inside a loop often slow, and how do you …

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: Awaiting inside a loop runs independent tasks one after another, so the total time is the sum of all tasks. Start the tasks together and await them as a group with Promise.all or Promise.allSettled, and add a concurrency limit when there are many tasks.

Detailed explanation

Look at for (const id of ids) { results.push(await fetchUser(id)); }. Each iteration waits for its request to finish before the next request starts. If you have 10 requests of 200 ms each, this takes about 2 seconds. They are independent, so they could all be in flight at the same time and finish in roughly 200 ms.

The fix is to separate starting work from waiting for it. A promise starts its work the moment it is created. So you create all the promises first, then await them together:

  • Promise.all resolves to an array of results in the same order as the input. It rejects as soon as any one promise rejects (fail-fast). The other operations are not cancelled; their results are simply ignored.
  • Promise.allSettled waits for every promise. It returns objects like { status: 'fulfilled', value } or { status: 'rejected', reason }. Use it when partial success is acceptable, such as sending notifications.
  • Sequential for...of with await is still correct when each step depends on the previous one, when order of side effects matters, or when an API forbids parallel calls.

Fully parallel is not always right either. Firing 5,000 requests at once can hit rate limits, exhaust database connections or run out of file descriptors in Node.js. In production you usually want bounded concurrency: at most N tasks running at a time. You can use a small worker pool or a library such as p-limit.

Example

// Slow: sequential, total time = sum of all requests
async function loadSequential(ids) {
  const users = [];
  for (const id of ids) {
    users.push(await fetchUser(id));
  }
  return users;
}

// Fast: parallel, total time is roughly the slowest request
async function loadParallel(ids) {
  return Promise.all(ids.map(id => fetchUser(id)));
}

// Bounded concurrency: at most `limit` tasks at once
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++;          // safe: JS runs this synchronously
      results[i] = await fn(items[i]);
    }
  }

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

// Usage
const users = await mapLimit(ids, 5, fetchUser);

The pool works without locks because JavaScript runs on a single thread. next++ can never be interrupted halfway by another worker.

Common mistakes

  • Using forEach with an async callback. ids.forEach(async id => { await save(id); }) does not wait for anything. forEach ignores the returned promises, so code after it runs immediately and rejections can go unhandled. Use for...of for sequential work or Promise.all(ids.map(...)) for parallel work.
  • Creating promises early but awaiting them one by one. Writing const a = taskA(); const b = taskB(); await a; await b; does run in parallel. But if b rejects while you are still awaiting a, Node.js may report an unhandled rejection. Wrapping both in Promise.all avoids this.
  • Assuming Promise.all cancels the remaining work on failure. It does not. If cancellation matters, use an AbortController and pass its signal to fetch or other abortable APIs.
  • Parallelising everything blindly. Unbounded Promise.all over thousands of items can overload a server or trigger HTTP 429 responses. Mention concurrency limits.

Follow-up questions

  • How do Promise.race and Promise.any differ, and when would you use each?
  • How would you add a timeout to an async operation using Promise.race or AbortController?
  • How would you retry failed tasks with exponential backoff while keeping a concurrency limit?

Interview tip: Do not just say "use Promise.all". Explain when sequential is required, when allSettled is better, and why production code needs a concurrency limit. That is what separates an experienced answer.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More hard JavaScript questions

All hard questions →

Related Questions

‹
Q2 of 10 · JavaScript
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA