Full answer
Two extremes are both bad for 10,000 API calls or file operations:
- Sequential await in a loop: safe but slow, because nothing overlaps.
- Promise.all over everything: starts all tasks at once. That can exhaust file descriptors (EMFILE), crush a database or trigger rate limits, and uses a lot of memory.
The balanced approach is a concurrency limit. A simple and correct pattern:
- Keep an index of the next task to run.
- Start N runner functions. Each runner loops: take the next index, run the task, store the result at that index, repeat until no tasks remain.
- await Promise.all(runners).
Because JavaScript is single-threaded, taking the next index (i++) is safe with no lock. Storing the result at the same index keeps the order of the output the same as the input.
Error policy needs a decision: fail fast (the first rejection stops new tasks) or collect errors per item (like allSettled). Retry with backoff for temporary failures.
Libraries such as p-limit, p-map and Node's own stream helpers (readable.map(fn, { concurrency })) do this. Use a library in production, but write the loop once so you understand it.
Choose N from the resource you protect: database pool size, API rate limit, or CPU count.
async function mapLimit(items, limit, task) {
const results = new Array(items.length);
let next = 0;
async function runner() {
while (next < items.length) {
const index = next++; // safe: JavaScript runs one callback at a time
results[index] = await task(items[index], index);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, runner));
return results;
}
// A pretend API call that takes a different time per item.
const fakeFetch = (id) => new Promise((resolve) => setTimeout(() => resolve('student-' + id), (id % 4) * 5 + 5));
async function main() {
let active = 0;
let maxActive = 0;
const ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const results = await mapLimit(ids, 3, async (id) => {
active++;
maxActive = Math.max(maxActive, active);
const value = await fakeFetch(id);
active--;
return value;
});
console.log('results in input order:', results.join(', '));
console.log('most tasks active at once:', maxActive);
}
main();Different delays per task mean they finish out of order, yet the output list keeps the input order. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): results in input order: student-1, student-2, student-3, student-4, student-5, student-6, student-7, student-8, student-9, student-10 most tasks active at once: 3
Key points
- Limit concurrency to protect resources.
- N runners pulling from a shared index is enough.
- Writing results by index keeps the order.
- Decide how errors are handled before you write the code.
Common mistakes
- Using Promise.all(items.map(task)) for thousands of items.
- Using array.forEach(async ...) and expecting the code to wait.
- Awaiting inside a for loop for independent tasks.
- Not deciding what happens when one task fails.
Follow-ups
- How would you add retry with exponential backoff?
- How do Node streams offer a concurrency option?
- How do you cancel pending tasks when one fails?
Tips
- Name the three options: sequential, unlimited, limited.
- Explain why i++ is safe without a lock.
- Mention p-limit as the library you would normally use.