Skip to main content

Function: withConcurrencyLimit()

@arolariu/website


@arolariu/website / lib/utils.client / withConcurrencyLimit

Function: withConcurrencyLimit()

withConcurrencyLimit<T>(tasks, limit?): Promise<T[]>

Defined in: lib/concurrency.client.ts:62

Executes async tasks with a concurrency limit using a sliding window approach.

Type Parameters

T

T

Return type of the async tasks

Parameters

tasks

() => Promise<T>[]

Array of async task functions to execute

limit?

number = 5

Maximum number of concurrent tasks (default: 5)

Returns

Promise<T[]>

Promise that resolves to array of task results (in original order)

Remarks

Use Cases:

  • Parallel file uploads (limit to 5 concurrent connections)
  • Batch API requests with rate limiting
  • Parallel image processing operations

Algorithm: Uses a sliding window that maintains at most limit tasks in flight at once. As tasks complete, new tasks are started to maintain the concurrency level.

Error Handling: Fail-fast: if ANY task throws, workers stop picking up new tasks and the returned promise rejects with the first error. Use withConcurrencyLimitAndProgress for per-task error tolerance.

Performance:

  • Time complexity: O(n) where n is number of tasks
  • Space complexity: O(limit) for the executing queue

Examples

// Upload 32 files with max 5 parallel connections
const uploadTasks = files.map(file => async () => {
const response = await fetch(file.sasUrl, {
method: 'PUT',
body: file.data
});
return {fileId: file.id, success: response.ok};
});

const results = await withConcurrencyLimit(uploadTasks, 5);
// Process images with concurrency control
const processTasks = images.map(img => async () => {
const processed = await processImage(img);
return processed;
});

const processed = await withConcurrencyLimit(processTasks, 3);
// was this page useful?