【问题标题】:When do event listeners get attached in Node.js?Node.js 中何时附加事件侦听器?
【发布时间】:2016-02-18 11:59:41
【问题描述】:

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

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)

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

【问题讨论】:

    标签: javascript node.js node-redis


    【解决方案1】:

    这是可能的,但是当你像你一样运行彼此相邻的命令时就不行了。此代码将给出与您粘贴相同的错误:

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

    在您的代码中不会发生这种情况的原因是节点线程在您的线程中运行时不会屈服于事件处理,因此事件处理将在附加错误处理程序之后发生。

    您可以在全局范围内侦听未捕获的错误事件,以捕获在附加之前发生的错误。

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

    【讨论】:

    • 客户端不会屈服于事件处理?你能解释更多吗?
    • 您创建客户端并添加处理程序的线程将继续运行,并且在从线程返回到事件循环之前不允许处理错误事件。看这里:stackoverflow.com/questions/8982489/…quora answer。对其余代码执行setTimeout(func, 0) 是强制返回偶数循环的一种方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多