简体   繁体   English

setTimeout不能与Node.js中的Monq一起使用

[英]setTimeout not working with Monq in Node.js

While attempting to use setTimeout to perform rate limiting on a monq worker, why is the worker not being throttled? 在尝试使用setTimeoutmonq worker执行速率限制时,为什么工作者没有受到限制?

worker does not wait for 10 seconds before executing setTimeout() . worker在执行setTimeout()之前不会等待10秒。 Why is this and how can we get it to delay the call to foo() ? 为什么这样,我们怎么能让它延迟调用foo()

var monq = require('monq')
var client = monq('localhost/mydb')
var worker = client.worker(['general'])
worker.register({
    test: function(params, callback) {
        try {
            setTimeout(foo(params, callback), 10000)
        } catch(err) {
            callback(err)
        }
    }
})

foo = function(params, callback) {
    console.log('Hello world')
    callback()
}

Because setTimeout expects a function reference. 因为setTimeout需要一个函数引用。 Instead, you're executing the function and passing the result to setTimeout . 相反,您正在执行该函数并将结果传递给setTimeout

Use: 采用:

setTimeout(function() {
    foo(params, callback);
}, 10000);

Also, the try/catch block is somewhat redundant there, because the call to setTimeout won't throw an exception. 此外,try / catch块在某种程度上是多余的,因为对setTimeout的调用不会引发异常。 Instead, you would need to handle it inside foo . 相反,你需要在foo处理它。

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

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