2014-02-05 60 views

回答

1

正如在其他答案中指出的那样,在单个回调中包装多个函数是微不足道的。但是,事件发射器模式有时更适合处理这种情况。示例可能是:

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); 

您可以根据需要添加尽可能多的侦听器。当然,这假设你想让你的回调注册的是事件发布器。很多时候这是真的。

-1

您可以为创建一个小模块:

jj.js文件:使用

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

例如:

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])) 
3

是有一些原因,你不能把一个包装两个函数,然后使用包装作为回调?例如:

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

request('http://...',handleCallback); 
相关问题