1

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?

Fusscreme
  • 152
  • 9
  • 1
    try logging response.ok and check the network behaviour when slow, which error code is coming from server and is it a OK response? – Harsh Mehta Oct 13 '21 at 07:48
  • I cannot reproduce the error, unfortunately. But the backend did receive the request and created an object. So I am quite sure that it send a successful status code. – Fusscreme Oct 13 '21 at 07:53
  • 1
    Code seems fine, may be server is the culprit? – Harsh Mehta Oct 13 '21 at 07:54
  • 1
    If you're on chrome (or potentially other browsers), you can open up your developer tools and navigate to the Network tab. You can then switch between different connection speeds ("No throttling", "Fast 3G", etc.) - that might help you reproduce the error and enable you to debug if you believe it is occuring due to a slow internet connection – Nick Parsons Oct 13 '21 at 07:59
  • 3
    Are you sure that you are sending the request only once? A Promise can only be "pending", "rejected" or "fulfilled", so the second `then` and `catch` can only both be called if the second `then` throws an error. – Taxel Oct 13 '21 at 08:05
  • Thank you for the hint with the throttling. I checked in the network tab, it is only sent once. But if the `then` and `catch` can only be called if the `second` fails, then I must be wrong about the perceived order of execution. Thank you everybody. – Fusscreme Oct 13 '21 at 09:28

0 Answers0