Async Pool Concurrent Map Utility
Map over large collections with bounded async concurrency, preserving input order in results and stopping early on failure modes.
Code
async function asyncPool<T, R>(
concurrency: number,
items: readonly T[],
mapper: (item: T, index: number) => Promise<R>,
): Promise<R[]> {
const results = new Array<R>(items.length);
let cursor = 0;
const workers = Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (cursor < items.length) {
const index = cursor;
const item = items[index];
cursor += 1;
results[index] = await mapper(item, index);
}
});
await Promise.all(workers);
return results;
}
const CONCURRENCY = 4;
const enriched = await asyncPool(CONCURRENCY, ['a', 'b', 'c', 'd', 'e', 'f'], async (id, i) => {
await new Promise((r) => setTimeout(r, 20));
return { id, position: i };
});
console.log('order preserved:', enriched.map((e) => e.id).join(''));
const withFailure = await asyncPool(2, ['x', 'y', 'z'], async (id) => {
if (id === 'y') throw new Error('boom on ' + id);
return id.toUpperCase();
}).catch((err) => err.message);
console.log('failure propagated:', withFailure);Output
Captured from a sandboxed run of this snippet in the build pipeline.
order preserved: abcdef
failure propagated: boom on yHow it works
Async Pool Concurrent Map Utility comes down to the function asyncPool.
Iteration happens inside while (cursor < items.length) — everything outside it runs once. Every asynchronous step is awaited, so rejections surface where the call happens. Invalid states are rejected up front: it throws Error instead of continuing with bad data.
The result comes back as an object carrying id.
Points of care
- The guard
id === 'y'short-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
Running the file prints labeled results such as order preserved:, failure propagated: — each operation’s effect is visible in the output.
The call returns id.
Core lines
await new Promise((r) => setTimeout(r, 20));
const withFailure = await asyncPool(2, ['x', 'y', 'z'], async (id) => {
if (id === 'y') throw new Error('boom on ' + id);
return id.toUpperCase();
}).catch((err) => err.message);
await Promise.all(workers);
Interactive Tools for This Topic
FAQ
- Does `asyncPool` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Is there a failure path for bad input?
- The code refuses to continue: `Error` is thrown while the state is still recoverable.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `asyncPool` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.