Вопрос

How can I callback two function in node?

For example:

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

Is there any module for that?

Это было полезно?

Решение 2

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.

Другие советы

Is there some reason you can't put a wrapper around the two functions, then use the wrapper as a callback? For example:

function handleCallback(data)
{
    func1(data);
    func2(data);
}

request('http://...',handleCallback);

You can create a little module for that:

jj.js file:

module.exports.series = function(tasks) {
    return function(arg) {
        console.log(tasks.length, 'le')
        require('async').eachSeries(tasks, function(task, next) {
            task.call(arg)
            next();
        })
    }
}

example of use:

var ff = require('./ff.js')

    function t(callback) {
        callback('callback')
    }

    function a(b) {
        console.log('a', b)
    }

    function b(b) {
        console.log('b', b)
    }


t(ff.series([a, b]))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top