- Home
- Interview Questions
- JavaScript
- 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
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.allresolves 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.allSettledwaits 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...ofwith 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
forEachwith an async callback.ids.forEach(async id => { await save(id); })does not wait for anything.forEachignores the returned promises, so code after it runs immediately and rejections can go unhandled. Usefor...offor sequential work orPromise.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 ifbrejects while you are still awaitinga, Node.js may report an unhandled rejection. Wrapping both inPromise.allavoids this. - Assuming
Promise.allcancels the remaining work on failure. It does not. If cancellation matters, use anAbortControllerand pass its signal tofetchor other abortable APIs. - Parallelising everything blindly. Unbounded
Promise.allover thousands of items can overload a server or trigger HTTP 429 responses. Mention concurrency limits.
Follow-up questions
- How do
Promise.raceandPromise.anydiffer, and when would you use each? - How would you add a timeout to an async operation using
Promise.raceorAbortController? - 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
- How do HttpOnly, Secure and SameSite cookie flags protect against XSS and CSRF? · 1 ans
- Why can't try/catch catch an error thrown inside a setTimeout callback or a promise? · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · 1 ans
Related Questions
- What is the difference between a view and a materialized view, and when would you use each? · SQL · 1 ans
- What does an async function return, and how does await pause execution without blocking? · JavaScript · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · JavaScript · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · JavaScript · 1 ans
- How do try, catch and finally work, and what happens if finally contains a return? · JavaScript · 1 ans
- Why can't try/catch catch an error thrown inside a setTimeout callback or a promise? · JavaScript · 1 ans
- What is the difference between localStorage, sessionStorage and cookies in the browser? · JavaScript · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)