문제

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