在下面的代码中,setTimeout()在客户端关闭请求后继续运行。我该如何阻止它?
function doSomething(callback){
console.log('Doing something...');
callback();
}
app.get('/', (req, res) => {
function waitTilDone(){
setTimeout(function(){
doSomething(waitTilDone);
}, 2000);
}
doSomething(waitTilDone)
});
答案 0 :(得分:2)
Express Request
是节点IncomingMessage
的增强版,其中包含end
,aborted
和app.get('/', (req, res) => {
var timer = 0;
req.on('aborted', function() {
if (timer) {
clearTimeout(timer);
}
});
function waitTilDone(){
timer = setTimeout(function(){
doSomething(waitTilDone);
}, 2000);
}
doSomething(waitTilDone)
});
个事件。挂钩到最合适的事件并清除超时。例如:
{{1}}