AsyncQueue Async Queue
AsyncQueue is a TypeScript class that implements the Symbol.asyncIterator interface and can be consumed by a for-await-of loop. It solves the problem where "a producer asynchronously produces some values, and one or more consumers asynchronously consume them," often used to limit concurrency (e.g., network requests, task scheduling).
Core Features
- Async iteration: implements
Symbol.asyncIterator, so you can directlyfor await (const v of queue). - Multiple consumers / competing-consumers pattern: multiple consumers can share the same queue, and each value is only obtained by one of them, naturally supporting concurrency limiting.
- Backpressure control: provides a simple
backpressure(max)method that can be awaited before enqueuing to prevent the queue length from exceeding a threshold. - Zero dependencies: backed by a self-implemented linked list (
LinkedQueue), with no third-party runtime dependencies.
Environment Requirements
- Node.js runtime (must support
Symbol.asyncIteratorandfor-await-of, usable on Node 10+; the development environment is based on Node 20). - The package is published in both ESM and CJS formats, with built-in
.d.tstype declarations, so TypeScript can be used directly.
Installation
bash
npm install @ai-zen/async-queue
# or
pnpm add @ai-zen/async-queueQuick Example
ts
import AsyncQueue from "@ai-zen/async-queue";
const queue = new AsyncQueue<number>();
(async () => {
for (const v of [1, 2, 3]) {
queue.push(v);
}
queue.done();
})();
for await (const v of queue) {
console.log(v); // 1 2 3
}For more complete usage, see Quick Start and API Reference.
Reference
- Quick Start — installation, creating instances, single/multiple consumer examples, backpressure example.
- API Reference —
constructor,push,shift,done,size,backpressure, etc.