什么时候事件监听器被附加到Node.js中?

我正在使用node-redis模块连接到redis。
所以,我附加了一个事件监听器来处理redis服务器连接无法build立的情况。

client = redis.createClient(6379, 'localhost') client.on('error',(err)=>{ console.log('redis connection refused') }) 

这是没有侦听器的情况下发生的错误。

 events.js:141 throw er; // Unhandled 'error' event ^ Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379 at Object.exports._errnoException (util.js:837:11) at exports._exceptionWithHostPort (util.js:860:20) at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14) 

现在我的问题是,这个事件监听器何时被附加到“客户端”。 连接事件监听器之前是否有可能引发连接拒绝错误?

这是可能的,但是当你像这样运行相邻的命令时不行。 这段代码会给你粘贴的错误:

 client = redis.createClient(6379, 'localhost') setTimeout(function() { client.on('error',(err)=>{ console.log('redis connection refused') }) }, 3000); 

在代码中不会发生这种情况的原因是节点线程在线程中运行时不会产生事件处理,所以在连接error handling程序之后会发生事件处理。

您可以全局侦听未捕获的错误事件,以捕获可能附着之前发生的错误。

 process.on('uncaughtException', (err) => { console.log('whoops! there was an error'); });