parallel
Runs an async mapper over an array with a concurrency limit (worker-pool semaphore). Results preserve input order and follow the Promise.allSettled shape — fn errors never reject the call.
Try it
Section titled “Try it”Import
Section titled “Import”import { parallel } from "1o1-utils";import { parallel } from "1o1-utils/parallel";Signature
Section titled “Signature”async function parallel<T, R>({ items, concurrency, fn, signal,}: ParallelParams<T, R>): Promise<Array<ParallelSettledResult<R>>>Parameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| items | readonly T[] | Yes | Items to process |
| concurrency | number | Yes | Max in-flight tasks (positive integer) |
| fn | (item: T, index: number) => Promise<R> | R | Yes | Mapper invoked per item; may be sync or async |
| signal | AbortSignal | No | Cancels pending work; in-flight tasks finish normally |
Returns
Section titled “Returns”Promise<Array<{ status: "fulfilled"; value: R } | { status: "rejected"; reason: unknown }>> — entries in input order.
Examples
Section titled “Examples”const results = await parallel({ items: urls, concurrency: 3, fn: async (url) => (await fetch(url)).json(),});
for (const r of results) { if (r.status === "fulfilled") console.log(r.value); else console.error(r.reason);}
// With AbortSignalconst controller = new AbortController();setTimeout(() => controller.abort(), 5000);
await parallel({ items, concurrency: 5, signal: controller.signal, fn: doWork,});Edge Cases
Section titled “Edge Cases”- Empty
itemsresolves to[]. concurrency >= items.lengthruns everything in parallel.concurrency: 1runs serially.- Errors thrown by
fnare captured as{ status: "rejected", reason }— the call itself never rejects from them. - Throws if
signalis already aborted at call time. - Once
signalaborts, unstarted indices resolve as rejected withsignal.reason; in-flight tasks complete and their results are recorded. - Throws if
itemsis not an array,concurrencyis not a positive integer,fnis not a function, orsignalis not anAbortSignal.
Also known as
Section titled “Also known as”concurrency limit, semaphore, worker pool, async map, throttle parallel
Prompt suggestion
Section titled “Prompt suggestion”I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use parallel to fetch 100 URLs with a concurrency cap of 5