-
Notifications
You must be signed in to change notification settings - Fork 369
Description
I'd like an option to have a timeout/deadline for the server to respond, so that if the response doesn't arrive within a specified number of seconds, the fetch promise is rejected and internally (i.e. without any sort of abort/cancellation API exposed to JS) the request is aborted by the browser on the TCP/IP level, so that bandwidth is not wasted in case the response does come later.
fetch('/slow', {deadline: 5000})
.then(called_if_response_is_quick, called_if_response_is_too_slow);
It'd be less wasteful equivalent of:
const oldfetch = fetch;
fetch = function(input, opts) {
return new Promise((resolve, reject) => {
setTimeout(reject, opts.deadline);
oldfetch(input, opts).then(resolve, reject);
});
}
I wouldn't mind if the timeout was automagically propagated to response.json()
, so that promise would be rejected too after the deadline.
Use-cases:
- Overloaded web servers. Servers may accept connections quickly (e.g. by a reverse proxy or incoming-connection worker thread) even if they don't have "back-end" capacity to process the request, so requests are getting queued and responses won't be generated in a timely fashion.
- Mobile connections with a very weak signal. Tethering via WiFi to a mobile device with no or weak signal.
In such cases it seems that the browser is unaware that it has an unusable network connection, makes a request and never gives up waiting for a response (perhaps the request was successfully sent or at least was buffered somewhere along the way).
In such cases adding a deadline helps identify unusable network or servers quicker (the developer knows how fast the server is supposed to respond) and allows the application react to the situation rather than getting stuck forever (or for as long as very conservative deadlines are built into the browser or networking stack) or worse, having open and unusable connections exhaust browser's limit of open connections.