项目作者: jfet97

项目描述 :
Communicating Sequential Processes in JavaScript
高级语言: TypeScript
项目地址: git://github.com/jfet97/csp.git
创建时间: 2019-03-20T11:45:45Z
项目社区:https://github.com/jfet97/csp

开源协议:MIT License

下载


@jfet97/csp

A library for Communicating Sequential Processes, built on top of async/await and the asynchronous iterable interface.

npm version

Installation

This library requires async/await and for-await-of support.

  1. $ npm install --save @jfet97/csp

Docs

You can find the documentation here.

Example Usage

Below is a trivial example of usage, that plays on the standard ping-pong example.

  1. const { Channel } = require('@jfet97/csp');
  2. const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
  3. const wiff = new Channel();
  4. const waff = new Channel();
  5. const createBall = () => ({ hits: 0, status: '' });
  6. const createBat = async (inbound, outbound) => {
  7. while (true) {
  8. const ball = await inbound.take(); // wait for an incoming ball
  9. ball.hits++;
  10. ball.status = ball.status === 'wiff!' ? 'waff!' : 'wiff!';
  11. console.log(`🎾 Ball hit ${ball.hits} time(s), ${ball.status}`);
  12. await timeout(500); // assume it's going to take a bit to hit the ball
  13. await outbound.put(ball); // smash the ball back
  14. }
  15. };
  16. createBat(waff, wiff); // create a bat that will wiff waffs
  17. createBat(wiff, waff); // create a bat that will waff wiffs
  18. waff.put(createBall());

ping pong

Async Iteration Protocol

Channels implement the async iterable interface, so you can transform the following illustrative code:

  1. async function process (inbound, outbound) {
  2. while (true) {
  3. const msg = await inbound.take();
  4. // do stuff with msg
  5. await outbound.put(res);
  6. }
  7. };

into a cleaner version, thanks to the powerful for-await-of:

  1. async function process (inbound, outbound) {
  2. for await(const msg of inbound) {
  3. // do stuff with msg
  4. await outbound.put(res);
  5. }
  6. };

Credits

Thanks to Joe Harlow for his work on this topic. If you are unfamiliar with CSP, I encourage you to see his talk where he describe a simpler version of this library as well.

Contributions

Contributions are welcomed and appreciated!

  1. Fork this repository.
  2. Make your changes, documenting your new code with comments.
  3. Submit a pull request with a sane commit message.

Feel free to get in touch if you have any questions.

License

Please see the LICENSE file for more information.