Skip to content

Instantly share code, notes, and snippets.

@jonchurch
Created February 19, 2020 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonchurch/85f787e51bf4cf2fd821046a6b9bca0d to your computer and use it in GitHub Desktop.
Save jonchurch/85f787e51bf4cf2fd821046a6b9bca0d to your computer and use it in GitHub Desktop.
Thinking through timeouts
const https = require('https');
const options = {
host: 'exoplanetarchive.ipac.caltech.edu',
path: '/cgi-bin/nstedAPI/nph-nstedAPI?table=exoplanets&select=*&format=json',
// apply an initial timeout which will apply to the connect event
timeout: 2000,
};
const beforeRequest = Date.now();
function handleResponse(res) {
const resReceived = Date.now();
console.log(
`${resReceived -
beforeRequest} ms elapsed between creating req and receiving res`
);
// uncomment this line to force a timeout if 20ms elapse between packets
// req.socket.setTimeout(20);
// there is no end event unless we listen to the data event
res.once('data', chunk => {});
res.on('end', () => {
console.log(`Entire response received in ${Date.now() - resReceived}`);
});
}
const req = https.request(options, handleResponse);
// set timeout which will be applied after the connect event is fired
// This particular API can be slow, so sometimes it may take more than 5 seconds to send response
// Tweak this number if you see lots of timeouts before getting the response,
// bring it to a value where you about 25% of the time
req.setTimeout(5000);
req.on('timeout', () => {
console.error(
`!!!!! request timeout ${Date.now() -
beforeRequest} ms before timeout event fired`
);
req.abort();
});
req.on('error', () => {});
req.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment