Gozala / channel

CSP style channel implementation, for the Channel specification
35 stars 3 forks source link

should this example work? #3

Closed darrencruse closed 9 years ago

darrencruse commented 9 years ago

Hi Gozala this is really just a question (it might be an issue but might not).

I was trying this module out today and I was esp. interested in using it with generators.

Can you see something wrong with the simple "example.js" I wrote below? It doesn't seem to work don't know if I've done something wrong or what:

var chan = require("channel");

console.log('making the channel');
var ch = new chan.Channel();

chan.spawn(function * () {
  while(true) {
    console.log('putting 1');
    yield ch.put(1);
    console.log('putting 2');
    yield ch.put(2);
    console.log('back from putting 2');
 }
});

chan.spawn(function * () {
  while(true) {
    console.log('reading 1');
    console.log(yield ch.take());
    console.log('reading 2');
    console.log(yield ch.take());
    console.log('back from reading 2');
 }
});

console.log('end');

Then output I get running "node --harmony example.js" is:

making the channel
putting 1
reading 1
end

Which I guess mean my puts and takes never resolved?

Gozala commented 9 years ago

Hi @darrencruse

As a side note, spawn does return a promise so you could inspect what's going on as follows:

 var chan = require("channel");

console.log('making the channel');
var ch = new chan.Channel();

var writer = chan.spawn(function * () {
  while(true) {
    console.log('putting 1');
    yield ch.put(1);
    console.log('putting 2');
    yield ch.put(2);
    console.log('back from putting 2');
 }
});

var reader = chan.spawn(function * () {
  while(true) {
    console.log('reading 1');
    console.log(yield ch.take());
    console.log('reading 2');
    console.log(yield ch.take());
    console.log('back from reading 2');
 }
});

reader.then(console.log, console.error);
writer.then(console.log, console.error);

With that code you can error like:

> [TypeError: undefined is not a function]

Which I'm afraid isn't very helpful :) The issue is that channel unlike in clojure do no have put or take methods instead channel has input and output ports so you would want to do ch.output.put(data) and ch.input.take() instead.

Gozala commented 9 years ago

So your code will look more like this:

var channel = require("channel");

console.log('making the channel');
var pipe = new channel.Channel(),
    input = pipe.input,
    output = pipe.output;

chan.spawn(function * () {
  while(true) {
    console.log('putting 1');
    yield output.put(1);
    console.log('putting 2');
    yield output.put(2);
    console.log('back from putting 2');
 }
});

chan.spawn(function * () {
  while(true) {
    console.log('reading 1');
    console.log(yield input.take());
    console.log('reading 2');
    console.log(yield input.take());
    console.log('back from reading 2');
 }
});

console.log('end');