When a TypeScript service fetches many URLs, starting every request at once can overload the API it calls or use more connections and memory than the service can handle. A worker pool limits the number of requests running at the same time. Each worker starts one request, then claims another URL when that request finishes.
The pool below stores each result beside its original URL, including failures, so requests that finish out of order do not mix up the results. It also avoids creating a promise for every URL before work starts. The concurrency limit sets how many requests run at once. It does not set how many requests can start per second.
Start requests only when a worker claims a URL
Promise.all waits for promises and returns successful results in input order, but it does not control when the promises start. For example, Promise.all(urls.map(url => fetch(url))) calls fetch for every URL before Promise.all receives the array. The MDN reference for Promise.all explains how it collects results. A worker-pool example shows how to limit when work starts by giving workers task factories, which create promises only when called.
This pool creates no more than limit workers. Each worker takes the next array index before it waits for the task, then stores the result at that index. A worker takes the index synchronously, before yielding control, so another worker on the same JavaScript event loop cannot take that index too.
type Outcome<T> =
| { status: "fulfilled"; value: T }
| { status: "rejected"; reason: unknown };
type IndexedOutcome<T, R> = {
index: number;
item: T;
outcome: Outcome<R>;
};
async function mapConcurrent<T, R>(
items: readonly T[],
limit: number,
task: (item: T, index: number) => Promise<R>,
): Promise<IndexedOutcome<T, R>[]> {
if (!Number.isSafeInteger(limit) || limit < 1) {
throw new RangeError("limit must be a positive safe integer");
}
const results = new Array<IndexedOutcome<T, R>>(items.length);
let nextIndex = 0;
async function worker(): Promise<void> {
while (true) {
const index = nextIndex++;
if (index >= items.length) return;
const item = items[index]!;
try {
const value = await task(item, index);
results[index] = {
index,
item,
outcome: { status: "fulfilled", value },
};
} catch (reason) {
results[index] = {
index,
item,
outcome: { status: "rejected", reason },
};
}
}
}
const workerCount = Math.min(limit, items.length);
await Promise.all(
Array.from({ length: workerCount }, () => worker()),
);
return results;
}
Here, Promise.all receives only the worker promises, so it waits for no more than limit workers. Each worker catches task errors and records them, then continues to the next URL. If the input array is empty, the pool creates zero workers and returns an empty result array. The ! after items[index] tells TypeScript that the index points to an item after the bounds check.
Use the pool with a Fetch task that checks the HTTP status when the code calling it should treat unsuccessful responses as failures:
const outcomes = await mapConcurrent(urls, concurrencyLimit, async (url) => {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status} for ${url}`);
}
return (await response.json()) as unknown;
});
A Fetch promise rejects for failures such as a network error. An HTTP error status still produces a Response, so the promise does not reject for that status alone. Checking response.ok makes clear which responses this example treats as failures. If the task parses a response body, it returns the parsed value. If the request or parsing throws an error, the pool records it for that URL.
Keep each outcome with its URL
Requests can finish in a different order from the order they started. The pool writes each result into the slot for its input index, then returns the URL with its result. This avoids mixing up URLs and results when code adds each completed request to a new array.
Handle each outcome by checking its status:
for (const { item: url, outcome } of outcomes) {
if (outcome.status === "fulfilled") {
console.log("Fetched", url, outcome.value);
} else {
console.error("Failed", url, outcome.reason);
}
}
With this all-outcomes contract, the function resolves after every URL has succeeded or failed, and the returned array keeps the input order. This resembles Promise.allSettled, which also returns a result with a status for every input, in input order. Promise.allSettled alone does not limit how many requests run at once. The pool controls when requests start, and its result records keep each failure.
A different pool can stop taking URLs after it sees the first failure, then reject after its active requests finish. With this fail-fast contract, the caller does not get partial successes. Use it when the code calling the pool should reject the whole batch. Use a result for each URL when the caller needs to report or retry individual failures.
Choose a limit for the resource you need to protect
Set concurrencyLimit based on what you need to protect, such as the number of simultaneous requests a service allows or the resources available to your process. There is no safe value for every service. One example service test reports HTTP 429 responses above the threshold it tested. Another author discusses a separate email service that limits request rates. These examples describe those services, not a general limit for Fetch.
A concurrency limit does not enforce a quota on requests per second. When requests finish quickly, workers can start many URLs in one second without exceeding the number of requests active at once. If a provider limits how quickly requests can start, use a separate rate limit. Make sure each task starts only the work you want to limit. If a task starts several Fetch requests, the pool can run only a few tasks and still exceed the request limit.
Check the bound and ordering in tests
Test the pool with promises you control instead of relying on network timing. Track how many tasks are active and the highest number reached. Keep several tasks open and check that this peak never exceeds the limit. Then resolve the promises in reverse or mixed order and check that each result still matches its input URL.
Also test a task that rejects while another task is still pending. The all-outcomes pool shown here keeps taking remaining URLs, then resolves with a failure record for the rejected task. Test a task that throws before returning a promise too; the try block catches that error just like a rejected promise. For a fail-fast pool, test separately that it stops starting work after it sees a failure and waits for active tasks to finish.