Bounded Queue Backpressure Async
Implement a bounded async queue with backpressure that blocks producers when full for flow control.
Code
export class BoundedQueue<T>{private items:T[]=[];private waiters:Array<{resolve:(v:T)=>void;reject:(e:Error)=>void}>=[];constructor(private capacity:number){}async enqueue(item:T):Promise<void>{if(this.waiters.length>0){this.waiters.shift()!.resolve(item);return;}if(this.items.length<this.capacity){this.items.push(item);return;}await new Promise<void>((resolve,reject)=>{const check=()=>{if(this.items.length<this.capacity){this.items.push(item);resolve();}else setTimeout(check,10);};check();});}async dequeue():Promise<T>{if(this.items.length>0)return this.items.shift()!;return new Promise((resolve,reject)=>this.waiters.push({resolve,reject}));}get size(){return this.items.length;}}Inside the snippet
The code’s whole job belongs to the class BoundedQueue and the function check.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
A fresh value is allocated for the result; the arguments stay untouched.
Points of care
- The guard
this.items.length>0short-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
BoundedQueue is what another module would consume; nothing else here is load-bearing for callers.
Interactive Tools for This Topic
FAQ
- Does `BoundedQueue` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `check` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.