Node.js中的http.request超时callback

目前我使用下面的代码来处理超时:

var request = http.request(options); request.setTimeout(30000, function(){ //when timeout, this callback will be called }); request.on('error', function(e){ //on error when request, this callback will be called }); 

问题是,当删除服务器的响应和超时时间较慢时,有时会调用超时callback,有时会调用超时callback和错误callback (错误callback中的错误是ECONNRESET – 连接重置)

如果代码调用这两个callback函数,它会打破我的代码的逻辑,我如何保证只有一个callback将被称为超时情况? 非常感谢

这是一个使用计数器variables的快速而简单的方法:

 function onProblem(e) { if (onProblem.count > 0) return; ++onProblem.count; if (e) { // it was an error } } onProblem.count = 0; var request = http.request(options); request.setTimeout(30000, onProblem); request.on('error', onProblem);