Created
February 19, 2020 01:13
-
-
Save jonchurch/85f787e51bf4cf2fd821046a6b9bca0d to your computer and use it in GitHub Desktop.
Thinking through timeouts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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