Skip to content

terite/event-race

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

event-race

What it does

It attaches groups of event handlers to event emitters, and removes them all once the first event has been emitted.

Why is it useful?

Consider the following

app.post('/sayhello', function (req, res) {
    var socket = net.connect(1337, 'helloserver');
    socket.on('connect', function () {
        res.send(200, 'said hello!');
        socket.write('Hello!');
    });
    socket.on('error', function () {
        res.send(500, 'error connecting');
    });
});

Both handlers call res.send, so only one can fire without a crash. If error is emitted for any reason after connect, the app will crash. Here's the alternative:

var race = require('event-race');
app.post('/sayhello', function (req, res) {
    var socket = net.connect(1337, 'helloserver');
    race(socket, {
        connect: function () {
            res.send(200, 'said hello!');
            socket.write('Hello!');
        },
        error: function () {
            res.send(500, 'error connecting');
        }
    });
});

Examples

1. race(emitter, event_names_array, handler)

var race = require('event-race'),
    stream = net.connect(1337, 'example-host');

race(stream, ['connect', 'error'], function (winner, args) {
    if (winner == 'connect') {
        // Successful connection
    } else {
        // Error while connecting
    }
});

2. race(emitter, event_names_and_handlers_object)

var race = require('event-race'),
    stream = net.connect(1337, 'example-host');

race(stream, {
    connect: function () { /* Successful connection */ }
    error: function (e) { /* Error while connecting */ }
});

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published