mpmc
Async multi-producer, multi-consumer FIFO queue communication utilies.
This is an experimental Typescript library for working with asynchronous streams
of data with a similar API to Rust standard module
mpsc
.
The core building block of this library is function onceChannel
which returns
a Promise
with the resolve
function.
function onceChannel() {
let resolve;
const promise = new Promise((r) => (resolve = r));
return [resolve, promise];
}
On top of onceChannel
is built function channel
which returns a
Sender
and Receiver
.
channel<T>(): [Sender<T>, Receiver<T>]
Sender
and Receiver
classes loosely
follow the API of Rust
Sender
and
Receiver
.
class Sender<T> {
send(...arg: NonNullable<T>[]): boolean;
}
class Receiver<T> {
recv(): Promise<T | null>;
close(): boolean;
forEach(f: (arg: T) => unknown): Promise<void>;
collect(): Promise<T[]>;
}
Sender.send
method takes non-nullable argument because null
is used to
denote that Receiver
has been closed. Receiver
also implements
asyncIterator
protocol to enable it being used in a for loop.
for await (const msg of receiver) {
// ...
}