go
-language like Channel. CSP-style channel.
日本語
PREPARE
$ npm install channel-light --save

USAGE
Channel = require('channel-light')
prepare Channel.
var Channel = require('channel-light');
channel = new Channel(callback,...)
make new channel.
var channel = Channel();
make new channel with 3 callbacks.
var channel = Channel(
function (err, val) {},
function (err, val) {},
function (err, val) {}
);
callback(err, val)
callback format. this
is channel itself.
function callback(err, val) {
}
channel = channel(callback,...)
add callback into channel for receive values.
channel(function (err, val) {});
channel(
function (err, val) {},
function (err, val) {}
);
channel = channel(err, val)
send values into channel.
channel(null, 'val1');
channel(null, 'val2');
channel(new Error('error'));
normalize callback arguments.
channel('val1');
channel('elem1', 'elem2');
channel(0);
channel(false);
channel(true);
QUICK EXAMPLE
void function () {
'use strict';
var Channel = require('channel-light');
var chan = Channel();
chan(function () {
console.log('start!');
setTimeout(this, 500, 'a');
}, function (err, val) {
console.log('a? ' + val);
setTimeout(this, 500, 'b');
}, function (err, val) {
console.log('b? ' + val);
setTimeout(this, 500, 'c');
}, function (err, val) {
console.log('c? ' + val);
console.log('end');
})();
}();
void function () {
'use strict';
var Channel = require('channel-light');
Channel(function () {
setTimeout(this, 3000, 'a2');
}, function (err, val) {
console.log('a2? ' + val);
setTimeout(this, 500, 'b2');
}, function (err, val) {
console.log('b2? ' + val);
setTimeout(this, 500, 'c2');
}, function (err, val) {
console.log('c2? ' + val);
var next = this;
setTimeout(function () {
next('d2');
}, 500);
}, function (err, val) {
console.log('d2? ' + val);
var next = this, arr = [], chan2 = Channel(
function (err, val) { console.log('e2 1st? ' + val); arr.push(val); },
function (err, val) { console.log('e2 2nd? ' + val); arr.push(val); next(arr); });
setTimeout(chan2, 300, 'e2X');
setTimeout(chan2, 200, 'e2Y');
}, function (err, arr) {
console.log('e2 arr: ' + arr.join(', '));
this('f21', 'f22', 'f23');
}, function (err, val) {
console.log('f2 values: ' + val.join(', '));
this(new Promise(function (res, rej) {
setTimeout(res, 500, 'g2');
}));
}, function (err, val) {
console.log('g2? ' + val);
console.log('end');
})();
}();
EXAMPLE USING aa (async-await)
$ npm install aa channel-light
communicate with 2 threads.
var Channel = require('channel-light');
var aa = require('aa');
aa(function *() {
yield wait(100, 'a');
var chan1 = Channel(), chan2 = Channel();
yield [
function *() {
yield wait(100);
chan2(null, 'request message');
yield chan1;
yield wait(100);
},
function *() {
yield wait(200);
yield chan2;
yield wait(100);
chan1(null, 'response message');
yield wait(100);
}
];
});
function wait(ms, val) {
return function (cb) { setTimeout(cb, ms, null, val); };
}
LICENSE
MIT
SEE ALSO