2

currently I used the following code to handle the timeout:

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

The problem is, when the remove server has a slow response and timeout, sometimes the timeout callback will be called, and sometimes both timeout callback and error callback will be called (the error inside the error callback is ECONNRESET - connection reset)

If the code call the both callback function, it will break my code's logic, how to I guarantee that only 1 callback will be called for timeout cases? Thanks very much

1 Answer 1

3

Here's a quick and easy way using a counter variable:

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);
Sign up to request clarification or add additional context in comments.

1 Comment

this tricks works, thanks. I found that even the clientRequest fired on('error', function(e)) callback, there is a possibilities that it fires on('response', function(response)) callback altogether, therefore it need to lock that callback too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.