Wednesday, September 15, 2010

Simple fab.stream

‹prev | My Chain | next›

Up tonight, a brief investigation of fab.stream in fab.js v0.5:
fab.stream = function stream( write, queue ) {
queue = queue || [];

var length = queue.length;

function drain( write, req ) {
for ( var i = 0; i < length; ) {
write = write.apply( undefined, queue[ i++ ] );
}

return write;
};

return function read() {
if ( !arguments.length ) return write ? write( drain ) : drain;

queue[ length++ ] = arguments;
return read;
}
}
It takes a callback argument along with a queue of items that can be replayed. Depending on what the upstream app from which fab.stream reads does, the queue can be further increased. For my purpose tonight, the queue is empty as is the upstream app call and I am supplying a callback, which reduces the function to this:
fab.stream = function stream( write ) {
function drain( write ) {
return write;
};

return function read() {
return write( drain )
}
}
So, when I create a fab.stream thusly:
return fab.stream(function callback (stream) {
// stream stuff
})()
... fab.stream returns the read() function, which is evaluated immediately by the trailing open-close parenthesis after the fab.stream() invocation. This, in turn, returns the result of invoking the function callback(), supplying the drain function as the stream callback.

Thus, anytime I call stream inside the callback() function, I am actually returning whatever function/callback/value I supply to it:
return fab.stream(function callback (stream) {
stream("foo");
})()
...would return the string "foo".

That is a long way to go to get access to the string "foo", so obviously that is not the primary reason to use fab.stream. In this case, with no queue and no upstream apps, the reason to use fab.stream is to be able to return the value of yet another callback/async function:
node> function async(cb) { return cb("foo")}
node> fab.stream(function callback (stream) { return stream( async ( function(v) { return v } ) ) } ) ()
'foo'
Well, I don't think I understand my problem from last night any better at this point, but I do think I'm getting a grip on fab.stream.

Day #227

No comments:

Post a Comment