Class: ConcurrencyQueue
new ConcurrencyQueue(limit = 5)
Creates a new concurrency queue.
Parameters:
limit– Maximum number of concurrent async operations. Default is5.
Properties:
limit– Maximum concurrency limit.activeCount– Current number of running operations.queue– Internal queue of waiting promises.
Method: run(fn)
Executes an asynchronous function within the concurrency queue.
Parameters:
fn– An async function (or function returning a promise) to execute.
Returns:
A promise resolving to the result of fn.
Behavior:
- If the number of currently running operations is below
limit,fnexecutes immediately. - If the limit is reached, the function waits in a queue until a slot is available.
- After
fnfinishes, the next function in the queue starts automatically.
Example Usage
1import { ConcurrencyQueue } from "hbh-nodes";3const queue = new ConcurrencyQueue(2);5async function task(id, delay) {6 console.log(`Task ${id} started`);7 await new Promise(r => setTimeout(r, delay));8 console.log(`Task ${id} finished`);9 return id;10}12// Run multiple tasks concurrently but limited to 2 at a time13const results = await Promise.all([14 queue.run(() => task(1, 1000)),15 queue.run(() => task(2, 500)),16 queue.run(() => task(3, 700)),17 queue.run(() => task(4, 300))18]);20console.log(results); // [1, 2, 3, 4]
Features
- Concurrency Limit: Only
limitasync operations run simultaneously. - Queueing: Additional calls wait in a FIFO queue.
- Automatic Execution: As soon as one task finishes, the next in queue starts automatically.
- Simple API:
run(fn)is all that’s needed to schedule tasks.
Notes
- Useful for limiting network requests, API calls, file operations, or any asynchronous workloads that must be throttled.
- Supports any async function, including ones returning promises.
- If no limit is specified, defaults to
5.