Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node callback and event emitter utilities #32

Open
zeroware opened this issue Dec 30, 2014 · 2 comments
Open

node callback and event emitter utilities #32

zeroware opened this issue Dec 30, 2014 · 2 comments

Comments

@zeroware
Copy link
Contributor

While using the lib I found that at some point people will have to use node callback and event emitter based lib with channels.

Here is two utilities functions I ended up with :

/**
 * Create a channel from an async node function
 * Passed function must accept a node callback as last args
 *
 * @param {function} f
 * @return {Channel}
 */
function fromNodeCallback(f) {

    var args = 2 <= arguments.length ? Array.prototype.slice.call(arguments, 1) : [];
    var chan = csp.chan();

    args.push(function(err, value) {
        csp.putAsync(chan, err ? err : value, function() {
            chan.close();
        });
    });

    f.apply(this, args);

    return chan;
}


/**
 * Create a channel from an event emitter object
 *
 * @param {function} eventEmitter
 * @param {string} eventName
 * @param {Channel} [chan]
 *
 * @return {Channel}
 */
function fromEvent(eventEmitter, eventName, chan) {

    chan = chan || csp.chan();

    eventEmitter.on(eventName, function(data) {
        csp.putAsync(chan, data);
    });

    return chan;
}
@ubolonton
Copy link
Contributor

fromEvent can be useful.

We have been holding off things like fromNodeCallback to wait for a better error handling story (#14).

@nmn
Copy link
Contributor

nmn commented Feb 11, 2015

I have pull request #37 for the same.

I think the error handling story is important to solve. But also, we need to decide on behaviour related to closed channels.

I think a closed channel should be a signal to remove all bindings. In the fromEvent function for example:

function fromEvent(eventEmitter, eventName, chan) {

    chan = chan || csp.chan();
    var handler = function(data){
        if(chan === csp.CLOSED){ // I need the documentation for this :(
            eventEmitter.off(eventName, handler);
        } else {
            csp.putAsync(chan, data);
        }
    }
    eventEmitter.on(eventName, handler);
    return chan;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants