node.js - Promise 超时后停止执行

标签 node.js callback promise q

我一直在使用 Q 模块来实现我正在从事的项目的 promise 。 我使用静态方法 Q.fncall() 从 node.js 样式函数创建 promise (基于返回 err,result 的回调)。

问题是我需要在一定时间后停止执行该函数,所以我使用了Q模块的“timeout”函数。因此,在 x 时间后,完成函数上的“错误”回调将执行,让我处理超时,但函数本身会继续执行,直到到达最终回调,即使处理程序不再监听。

问题是:有没有办法让函数执行超时后停止执行?我知道我可以在超时处理程序上设置一个变量,并在超时结束时继续检查函数,但我希望有一种更干净的方法来实现这一点。

代码如下:

        Q.nfcall(test1, id)
        .timeout(1000)
        .done(
            function (value) {
                console.log("SUCCESS: " + value);
            }, 
            function (reason) {
                console.log("ERROR " + reason);
            },
            function (progress) {
                console.log("PROGRESS " + progress);
            }
        );

和 test1 函数:

function test1(id,callback){
db_rw_pool.query("SELECT * FROM table WHERE id=?",[id], function(err,result) {
    if(err){
        callback(err,null);
    }
    else {
        setTimeout(function(){
            console.log("I DON'T WANT YOU TO BRE PRINTED")
            callback(null,result);
        },2000);

    }
    return;
});

}

在我的理想情况下,setTimeout(...,2000) 中的代码永远不应该被执行。这可能吗?

提前致谢。

最佳答案

我认为你对自己的担心太低了。一旦您运行了 test1,就无法阻止 db_rw_pool.query 的执行及其回调的调用(除非您在此 中采取特殊的预防措施>db_rw_pool.query 方法)。 SQL 查询的结果将会返回。问题是代码是否会在某个时刻吞掉这些结果。本例中的吞咽发生在 Q 的 timeout 方法的代码中。只需将您不想执行的任何代码放入 done 的 onFulfilled 处理程序中即可。

你写

The problem is that I need to stop the execution of said function after a certain amount of time, so I used the function "timeout" of the Q module.

超时方法不会阻止该函数的执行。相反,它会返回一个新的 Promise,如果它所绑定(bind)的 Promise(您使用 Q.nfcall 做出的 Promise)未在设定的时间段(在此为 1000 毫秒)内实现,则指示该新 Promise 失败。案例)。

如果您想阻止回调执行,您可以将其包装在一个检查时间的函数中。像这样的东西:

function stopExecutingAfter(timeout, fn) {
  var stopifAfter = Date.now() + timeout
  return function() {
    if(Date.now() > stopIfAfter) return
    fn.apply(null, arguments)
  }
}

Q 主要关注 promise ,所以很明显它不会为你做这件事。 使用这种技术,您可以创建一个返回 promise 的 nfcallWithTimeout 函数,同时保护传递的函数(通过将其包装在类似上面的内容中)。那么您就不必两次配置超时行为。

关于node.js - Promise 超时后停止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16479090/

相关文章:

javascript - 如何使用 node-mongodb-native 在 mongodb find() 的回调中返回一个临时集合?

c# - 将多个参数传递给 Threading.Timer 回调方法的最佳方法是什么?

android - DynamicListView 拖放 onDrop?

javascript - Protractor 的期望是否在内部等待 promise ?

node.js - 在 map 中使用多个等待

javascript - mongoose.Promise 和 promisifyAll 有什么区别?

android - cmd:命令失败,退出代码为 ENOENT

javascript - 如何在 Node.js/Express 中进行重定向(301)?

node.js - 使用 mongoose 插入或更新到 Mongodb 并在更新时修改内部元素

python - 使用导入模块中的变量向 QProgressBar 报告进度