I've encountered a unexpected behavior in my fetch code when the internet connection is slow. Consider the following code (not my actual code):
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
fetch("http://url")
.then(handleErrors)
.then(response => console.log("success") )
.catch(error => console.log("error") );
// "error"
// "success" (why is this called?)
The only way I can explain this behaviour is that the response is somewhat of an async function itself (check out https://stackoverflow.com/a/33446005/3016745). Meaning that first the request is sent, immediately after the connection times out and throws an error, and last the response is coming and calls the .then.
I checked the backend and the request and response both were successful.
Does this make sense? How do I prevent this behaviour?