node.js - Stop execution after promise times out -
i've been using q module implement promises on project i'm working on. i'm using static method q.fncall() create promise out of node.js style function (based on callbacks returning err,result).
the problem need stop execution of said function after amount of time, used function "timeout" of q module. so, after x amount of time, "error" callback on done function executes , let's me handle timeout function keeps getting executed until reaches final callback if handler not listening anymore.
the question is: there way stop execution of function after timeout executed? know can set variable on timeout handler , keep checking in function if timeout over, i'm hoping cleaner way of achieving this.
the code follows:
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); } );
and test1 function:
function test1(id,callback){ db_rw_pool.query("select * table id=?",[id], function(err,result) { if(err){ callback(err,null); } else { settimeout(function(){ console.log("i don't want bre printed") callback(null,result); },2000); } return; });
}
in ideal situation, code inside settimeout(...,2000) should never executed. possible?
thanks in advance.
i think you're concerning on low level. once you've ran test1
, there's no way stop db_rw_pool.query
executing, , callback being called (unless you'd take special precautions in db_rw_pool.query
method). results sql query come back. question whether code swallow these results @ point, or not. swallowing in case happens in code q's timeout
method. place code don't want executed in onfulfilled handler of done
.
you write
the problem need stop execution of said function after amount of time, used function "timeout" of q module.
the timeout method won't stop function executing. rather, returns new promise instructed fail if promise it's bound (the 1 you've made q.nfcall
) not fulfilled within set period (1000 ms in case).
if somehow want stop callback executing, wrap inside function checks time. like:
function stopexecutingafter(timeout, fn) { var stopifafter = date.now() + timeout return function() { if(date.now() > stopifafter) return fn.apply(null, arguments) } }
q concerns promises, it's obvious won't you. using technique, make nfcallwithtimeout
function returns promise while protecting passed function (by wrapping in above) well. don't have configure timeout behavior twice.
Comments
Post a Comment