@tios/chan
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

@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;
})();

Readme

Keywords

none

Package Sidebar

Install

npm i @tios/chan

Weekly Downloads

1

Version

0.1.4

License

MIT

Unpacked Size

12.1 kB

Total Files

14

Last publish

Collaborators

  • towyuan