Search code examples
node.jsnode-async

How to add two function as callback in node?


How can I callback two function in node?

For example:

request('http://...',[func1,func2])

Is there any module for that?


Solution

  • As noted in other answers it's trivial to wrap multiple functions in a single callback. However, the event emitter pattern is sometimes nicer for handling such cases. A example might be:

    var http = require('http');
    var req = http.request({ method: 'GET', host:... });
    
    req.on('error', function (err) {
        // Make sure you handle error events of event emitters. If you don't an error
        // will throw an uncaught exception!
    });
    
    req.once('response', func1);
    req.once('response', func2);
    

    You can add as many listeners as you like. Of course, this assumes that what you want your callbacks to be registered on is an event emitter. Much of the time this is true.