Implement a task queue with bounded concurrency and drain callbacks.
Concurrency limits are essential for preventing resource exhaustion when performing heavy IO operations (like network requests or database queries). Bounded queues buffer bursty traffic, ensuring you never execute more than N tasks simultaneously.
Implement the queue generator:
functioncreateAsyncQueue(concurrency){}
It should return an object exposing the following API:
queue.push(taskFn)// Returns Promise<result> or Promise.reject<error>queue.onDrain(callback)// Registers a callback to fire when idlequeue.size()// Number of tasks waiting to executequeue.pending()// Number of tasks currently executing
Core Behavior
Execute at most concurrency tasks at once.
Buffer excess tasks, starting them as soon as execution capacity opens up.
The Promise returned by push should firmly bind to the resolution/rejection of its underlying taskFn.
Executions that reject or throw an error must not halt the scheduler. The queue must continue processing remaining items.
Lifecycle & Draining
Registered onDrain callbacks must fire immediately upon the queue entering a completely idle state (both size() and pending() reach 0).
If new tasks are pushed while idle, the queue leaves the idle state. It should trigger drain callbacks again when it eventually returns to an idle state.
Examples
const queue =createAsyncQueue(2);// At most 2 parallel tasks// Task 1 & 2 start immediatelyqueue.push(()=>fetch('/api/1'));queue.push(()=>fetch('/api/2'));// Task 3 is buffered until 1 or 2 finishesqueue.push(()=>fetch('/api/3')).then(res=>console.log("Task 3 done!"));queue.onDrain(()=>{console.log("All tasks completed. Queue is idle.");});