@tios/chan
Go-like channels for JavaScript
Usage
const {Channel} = require('@tios/chan');
const {sleep} = require('./utils');
async function consume(chan) {
while (true) {
const item = await chan.recv();
console.log(`[CONSUMER] ${new Date()} received item ${item}`);
if (item === null) {
console.log('stopping consumer');
return;
}
await sleep(1000);
}
}
(async function main() {
const channel = new Channel(5);
// Start consumers
const c = consume(channel);
// Fill the channel
for (let i = 0; i < 10; ++i) {
console.log(`[PRODUCER] ${new Date()} sending item ${i}`);
await channel.send(i);
}
// Close the channel, which will make the consumers exit once they made the
// channel empty.
channel.close();
// Should exit consume
await c;
})();