AsyncIterableBuffer is a lightweight, stateful asynchronous buffer that allows you to push values and consume them using async iteration (e.g. for await...of
). It’s ideal for bridging event-driven or callback-based code with modern async/await patterns.
- Asynchronous Iteration: Implements the
AsyncIterableIterator
interface. - Push and Consume: Dynamically push values into the buffer and consume them asynchronously.
- Graceful Termination: Signal completion with an
end()
method and handle early termination viareturn()
. - TypeScript Support: Fully typed for TypeScript projects.
- Lightweight: No dependencies.
npm install async-iterable-buffer
import { AsyncIterableBuffer } from 'async-iterable-buffer';
const buffer = new AsyncIterableBuffer<number>();
// Push some values into the buffer.
buffer.push(1);
buffer.push(2);
buffer.push(3);
// Signal that no more values will be pushed.
buffer.end();
// Consume the buffer with async iteration.
(async () => {
for await (const num of buffer) {
console.log(num); // Outputs: 1, 2, 3
}
})();
import { AsyncIterableBuffer } from 'async-iterable-buffer';
const buffer = new AsyncIterableBuffer<string>();
// Start an async iterator.
(async () => {
for await (const value of buffer) {
console.log(value);
if (value === 'stop') {
// Terminate iteration early.
await buffer.return();
}
}
})();
// Push values asynchronously.
buffer.push('first');
buffer.push('stop');
buffer.push('ignored'); // This value won't be processed since the buffer is closed after "stop".