【问题标题】:http.request timeout callback in Node.jsNode.js 中的 http.request 超时回调
【发布时间】:2014-08-31 06:32:10
【问题描述】:

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

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
 });

问题是,当remove server响应慢且超时时,有时会调用超时回调,有时超时回调和错误回调都会被调用(error里面的error回调是 ECONNRESET - 连接重置)

如果代码调用两个回调函数,它会破坏我的代码逻辑,我如何保证超时情况只会调用1个回调?非常感谢

【问题讨论】:

    标签: javascript node.js timeout


    【解决方案1】:

    这是使用计数器变量的一种快速简便的方法:

    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);
    

    【讨论】:

    • 这个技巧有效,谢谢。我发现即使 clientRequest 触发了('error', function(e)) 回调,它也有可能完全触发('response', function(response)) 回调,因此它也需要锁定该回调
    猜你喜欢
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 2012-01-12
    • 2018-03-17
    • 2013-02-02
    • 2012-07-24
    • 1970-01-01
    • 2016-09-19
    相关资源
    最近更新 更多