CSP channels for Javascript (like Clojurescript's core.async, or Go) THIS IS AN UPSTREAM FORK

Related tags

Control Flow js-csp
Overview

js-csp

Communicating sequential processes for Javascript (like Clojurescript core.async, or Go).

Examples

var csp = require("js-csp");

Pingpong (ported from Go).

function* player(name, table) {
  while (true) {
    var ball = yield csp.take(table);
    if (ball === csp.CLOSED) {
      console.log(name + ": table's gone");
      return;
    }
    ball.hits += 1;
    console.log(name + " " + ball.hits);
    yield csp.timeout(100);
    yield csp.put(table, ball);
  }
}

csp.go(function* () {
  var table = csp.chan();

  csp.go(player, ["ping", table]);
  csp.go(player, ["pong", table]);

  yield csp.put(table, {hits: 0});
  yield csp.timeout(1000);
  table.close();
});

There are more under examples directory.

Documentation

This is a very close port of Clojurescript's core.async. The most significant difference is that the IOC logic is encapsulated using generators (yield) instead of macros. Therefore resources on core.async or Go channels are also helpful.

Supported runtimes

js-csp requires ES6 generators.

Firefox >= 27

Earlier versions of Firefox either had ES6 generators turned off, or supported only old style generators.

Node.JS >= 0.11.6

Run with --harmony or --harmony-generators flag. Check support using

node --v8-options | grep harmony

Chrome >= 28

Turn on an experimental flag. Look for "Enable Experimental JavaScript" at chrome://flags.

Other

Use one of the js-to-js compilers:

Or, if you use Python's Twisted: https://github.com/ubolonton/twisted-csp

Or, if you want a better language: https://github.com/clojure/core.async

Install

It's available for both npm and bower. For browsers, use browserify+npm or browserify+bower+debowerify.

npm install js-csp
bower install js-csp

Pre-built files for (old) browsers may be coming.

TODO

  • Test operations (map, filter, reduce, pipe...) more thoroughly.
  • Use better name for functions.
  • Better code style?
  • Multiplexing, mixing, publishing/subscribing.
  • Add more documentation and examples.
  • Add browser builds and tests.
  • Add conversion functions that "de-IOC" promises and callback-based APIs (e.g. Web Workers).
  • Investigate error handling in goroutines:
    • Special yield waitFor that either returns a value or throws an error from the result channel.
    • Exception propagation & stack capturing.
  • Explore how deep yields (yield*) affect composability.
  • Deadlock detector.
  • Hands-on examples.

Inspiration

License

Distributed under MIT License.

You might also like...

A workshop about JavaScript iteration protocols: iterator, iterable, async iterator, async iterable

A workshop about JavaScript iteration protocols: iterator, iterable, async iterator, async iterable

JavaScript Iteration protocol workshop A workshop about JavaScript iteration protocols: iterator, iterable, async iterator, async iterable by @loige.

Dec 20, 2022

Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

May 18, 2022

Async concurrent iterator (async forEach)

each-async Async concurrent iterator (async forEach) Like async.each(), but tiny. I often use async.each() for doing async operations when iterating,

Oct 21, 2022

Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

May 3, 2022

Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

Jan 3, 2023

⛰ "core" is the core component package of vodyani, providing easy-to-use methods and AOP implementations.

Vodyani core ⛰ "core" is the core component package of vodyani, providing easy-to-use methods and AOP implementations. Installation npm install @vodya

Oct 18, 2022

Lightweight WebSocket lib with socket.io-like event handling, requests, and channels

ws-wrapper Lightweight and isomorphic Web Socket lib with socket.io-like event handling, Promise-based requests, and channels. What? Much like Socket.

Dec 23, 2022

Virtual linear channels for ESPN+

Virtual linear channels for ESPN+

Virtual linear channels for ESPN+

Jan 3, 2023

App that allows you to control and watch YouTube videos using hand gestures. Additionally, app that allows you to search for videos, playlists, and channels.

App that allows you to control and watch YouTube videos using hand gestures. Additionally, app that allows you to search for videos, playlists, and channels.

YouTube Alternative Interaction App An app I made with Edward Wu that allows you to search and watch videos from YouTube. Leverages Google's YouTube D

Dec 28, 2021

A web app for seeing your recent Twitch chat mentions and/or other tracked words amongst channels you follow.

Mentions A web app for seeing your recent Twitch chat mentions and/or other tracked words amongst channels you follow. Requirements NodeJS. Client ID

Dec 22, 2022

🚀 Blazing fast thread channels integration for all Discord.js versions

djs-threads 🚀 Blazing fast thread integration for all Discord.js versions 😃 THIS PROJECT IS ARCHIVED this project is archived because Discord will c

Feb 28, 2022

A NodeJS package for voice channel interactions on Revolt. This package lets you join voice channels, play music and more!

Revoice.js - A Voice Module for Revolt This package is still in developement and lacks many features. You still are able to play sound to a voice chan

Dec 25, 2022

The simplest implementation of Golang channels, selects and wait groups

The simplest implementation of Golang channels, selects and wait groups

TypeScript Channels The simplest implementation of Golang channels, selects and wait groups Installation You can use one of the following package mana

Dec 8, 2022

Displays all hidden Channels, which can't be accessed due to Role Restrictions, this won't allow you to read them (impossible)

Who is the Creator ? The creator of this plugin is DevilBro I have completely reworked the plugin so that it can use the BDFDB library from DevilBro !

Dec 29, 2022

Displays all hidden Channels, which can't be accessed due to Role Restrictions, this won't allow you to read them (impossible)

Displays all hidden Channels, which can't be accessed due to Role Restrictions, this won't allow you to read them (impossible)

ShowHiddenChannels Plugin Returns DevilBro, author of this plugin, and BetterDiscord developers have deleted ShowHiddenChannels plugin from the offici

Sep 17, 2022

Feeds is a simple Revolt bot that delivers RSS feeds to your channels.

Feeds Feeds is a simple Revolt bot that delivers RSS feeds to your text channels. You can invite it here. Feeds are refreshed once per minute, and if

Dec 5, 2022

A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebWorker like neither of those.

Amuchina A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebW

Sep 17, 2022

JavaScript project for the Leaderboard list app, using Webpack and ES6 features, notably modules. this app consume the Leaderboard API using JavaScript async and await and add some styling.

Leaderboard Project JavaScript project for the Leaderboard list app, using Webpack and ES6 features, notably modules. this app consume the Leaderboard

May 20, 2022
Comments
  • For your Taming Async article...

    For your Taming Async article...

    You might like to consider using async-csp, which uses async/await instead of generators. I think it's much cleaner! I don't think js-csp is compatible with async/await, as it doesn't seem to return promises (or did I miss it?).

    opened by trusktr 2
  • <- macro for put has the channel and value reversed

    <- macro for put has the channel and value reversed

    just fyi I was playing with the macros and I'm pretty confident (I think?) there's a typo in that:

    binaryop (<-) 50 right {
      macro {
        case { $ctx $value $channel } => {
          letstx $csp = [makeIdent('csp', #{$ctx})];
          return #{ yield $csp.put($channel, $value) }
        }
      }
    }
    

    has the order of the $value and $channel reversed I believe it was meant to be:

    binaryop (<-) 50 right {
      macro {
        case { $ctx $channel $value } => {
          letstx $csp = [makeIdent('csp', #{$ctx})];
          return #{ yield $csp.put($channel, $value) }
        }
      }
    }
    

    After that little change I was successful in making this little example work btw:

    var { chan, timeout } = csp = require('js-csp');
    
    var ch = chan();
    
    go({
      var val;
      while((val = <- ch) !== csp.CLOSED) {
        console.log(val);
      }
    });
    
    foo = () => go({ return 3; });
    
    go({
      ch <- 1;
      var t = <- timeout(1000);
      ch <- 2;
      t = <- timeout(1000);
      ch <- (<- foo());
      ch.close();
    });
    

    happy to do a pull request btw wasn't sure I should for something so small I'll watch for comments in case you want me to

    opened by darrencruse 0
  • alts does receive

    alts does receive "null" from channels

    A channel, created with csp.go(function*().... will not yield and always return null in csp.alts.

    var t = csp.go(function*() {
        while(true) {
          var action = yield csp.take(csp.timeout(2000));
          return "test"
        };
    });
    

    A channel like "t" will not work with alts. alts will not wait for a new value from t - it will receive "null" immediatly and it will run a loop that freezes the browser.

    opened by ThomasDeutsch 0
Owner
James Long
James Long
Async utilities for node and the browser

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed f

Caolan McMahon 27.8k Dec 31, 2022
An async control-flow library that makes stepping through logic easy.

Step A simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless. How to install Simply cop

Tim Caswell 2.2k Dec 22, 2022
A solid, fast Promises/A+ and when() implementation, plus other async goodies.

when.js When.js is a rock solid, battle-tested Promises/A+ and when() implementation, including a complete ES6 Promise shim. It's a powerful combinati

The Javascript Architectural Toolkit 3.4k Dec 18, 2022
An extension to Async adding better handling of mixed Series / Parallel tasks via object chaining

async-chainable Flow control for NodeJS applications. This builds on the foundations of the Async library while adding better handling of mixed Series

Matt Carter 25 Jul 15, 2019
Handling iterables like lazy arrays.

Iterum iterum library provides a class for handling iterable transformations inspired in Array methods and lodash/fp functions. This library also supp

Xavier Garcia Buils 28 Nov 5, 2021
A promise library for JavaScript

If a function cannot return a value or throw an exception without blocking, it can return a promise instead. A promise is an object that represents th

Kris Kowal 15k Dec 30, 2022
Composable Concurrency Abstractions for JavaScript. :railway_track: :rhinoceros: :train: :vertical_traffic_light:

sporadic Composable Concurrency Abstractions for JavaScript. Example #!/usr/bin/env node (async () => { const sporadic = require('sporadic') cons

Marco Aurélio da Silva 16 Sep 24, 2022
An Implementation of Observables for Javascript

zen-observable An implementation of Observables for JavaScript. Requires Promises or a Promise polyfill. Install npm install zen-observable Usage impo

Kevin Smith 839 Dec 21, 2022
Highly performant JavaScript data stream ETL engine.

bellboy Highly performant JavaScript data stream ETL engine. How it works? Bellboy streams input data row by row. Every row, in turn, goes through use

Claviz 86 Dec 16, 2022
pattern matching in javascript & typescript made easy

?? matchbook pattern matching in typescript & javascript made easy matchbook is a lightweight & easy to use pattern matching library, for TypeScript a

@matchbook/ts 25 Dec 1, 2022