简体   繁体   English

是否有一种通用机制来在node.js中超时事件?

[英]Is there a general mechanism to timeout events in node.js?

I am learning node.js and most of examples I can find are dealing with simple examples. 我正在学习node.js,我能找到的大多数例子都是处理简单的例子。 I am more interested in building real-world complicated systems and estimating how well event based model of node.js can handle all the use cases of a real application. 我更感兴趣的是构建真实世界的复杂系统,并估计node.js基于事件的模型如何处理实际应用程序的所有用例。

One of the common patterns that I want to apply is let blocking execution to time-out if it does not occur within certain timeout time. 我想要应用的一个常见模式是,如果在某个超时时间内没有发生,则阻止执行超时。 For example if it takes more than 30 seconds to execute a database query, it might be too much for certain application. 例如,如果执行数据库查询需要超过30秒,那么对于某些应用程序来说可能太多了。 Or if it takes more than 10 seconds to read a file. 或者如果读取文件需要10秒以上。

For me the ideal program flow with timeouts would be similar to the program flow with exceptions. 对我来说,具有超时的理想程序流程与具有例外的程序流程类似。 If an event does not occur within certain predefined timeout limit, then the event listener would be cleared from the event loop and a timeout event would be generated instead. 如果事件未在某个预定义的超时限制内发生,则事件侦听器将从事件循环中清除,并且将生成超时事件。 This timeout event would have an alternate listener. 此超时事件将具有备用侦听器。 If the event is handled normally, then both the timeout listener and event listener are cleared from the event loop. 如果事件处理正常,则从事件循环中清除超时侦听器和事件侦听器。

Is there a general mechanism for timeout handling and cleaning up timed out processes? 是否存在超时处理和清理超时进程的一般机制? I know some types such as socket have timeout parameter but it is not a general mechanism that applies to all events. 我知道一些类型,如socket有超时参数,但它不是适用于所有事件的一般机制。

There is nothing like this at the moment (that i know of, but i don't know everything). 目前没有这样的事情(我知道,但我不知道一切)。

The only thing i can think of is that you reset it yourself somehow. 我唯一能想到的是你自己以某种方式重置它。 I've given an example below but I think it may have some scope issues. 我在下面给出了一个例子,但我认为它可能有一些范围问题。 Should be solvable though. 应该是可以解决的。

var to
function cb() {
    clearTimeout(to)
    // do stuff
}
function cbcb() {
    cb()
}
function cancel() {
    cb = function() {} // notice empty
}
fs.doSomethingAsync(file, cbcb)
to = setTimeout(cancel, 10000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM