DEV Community

[Comment from a deleted post]
Collapse
 
tqbit profile image
tq-bit • Edited

Good post. I'm happy to see fetch continues to gain ground within the dev community

That said, I haven't found much evidence of widespread

Kind of agree. That, however, is mainly caused by people using http - clients such as axios which are still powered by xhr-requests. Which is good, as fetch makes it a bit hard to observe upload / download progress.

But new libs are on the rise. See the npm - package bent for instance: npmjs.com/package/bent

I've seen examples where developers are mixing fetch() with old-style asynch and await structures.

Async - await is not old style, it's more of syntactic sugar over promises. Since fetch itself returns a promise and you only have access to e.g. the status from within the .then() - callback scope, If you try and provide an API that handles different status code, perhaps you could consider the following:

(async function () {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/todos')
    if (response.status >= 200 && response.status <= 399) {
      const data = await response.json(); 
      console.log(data); 
    }
    if (response.status === 400) {
      // handle client error
      // return result ...
    }
    if (response.status === 404) {
      // handle not found error
      // return result ...
    }

  } catch (e) {
    // ... handle serverside or network error
  }
})()
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mjoycemilburn profile image
MartinJ

Many thanks for your encouragement tq.

As you'll have gathered I'm no expert on any of this stuff, so feedback is important to me.

I had a look at "bent" - very interesting, but I'm wary of using external libraries. What I particularly like about fetch() is that it's built into the standards (albeit these seem to be a bit of a patchwork).

I should have chosen my words more carefully when I described "await" as old hat. I meant in the specific context of this application. If you /really/ wanted to inspect server response statuses in a classic fetch() implementation could you not do this in the .catch() function - ie without the need for asynch/await

Best wishes, MJ

Collapse
 
tqbit profile image
tq-bit

Hello MJ,

thank you for your reply.

I've got to agree, fetch is a little underrepresented in the docs. I'm keeping a small template to boilerplate for several usecases in Notion, perhaps you could make use if it as well.

notion.so/Browser-s-fetch-API-73e8...

If you /really/ wanted to inspect server response statuses in a classic fetch() implementation could you not do this in the .catch() function - ie without the need for asynch/await

As far as I understand, .catch() is fired when an error with the executed code occurs.

Say you try and resolve your fetched data stream to json with response.json(), but there really is no body that could be converted. In that case, your .catch() block will throw you an error like this:

SyntaxError: Unexpected token U in JSON at position 0

You could alternatively try and handle the status inside the first .then() - block, like it's shown in this (google docs blog)[developers.google.com/web/ilt/pwa/...]. After all, choosing between .then and async / await is also a matter of personal or team preference.

fetch('examples/example.json')
.then(function(response) {
  if (!response.ok) {
    // if (response.status === 400) {/* ... */}
    // if (response.status === 401) {/* ... */} 
    // ...
  }
  // Do stuff with the response
})
.catch(function(error) {
  console.log('Looks like there was a problem: \n', error);
});
Enter fullscreen mode Exit fullscreen mode
 
mjoycemilburn profile image
MartinJ

Gosh - you're absolutely right. It's there in the Mozilla docs too - "the fetch() method ... returns a Promise that resolves to the Response to that request — as soon as the server responds with headers — even if the server response is an HTTP error status." In bold text too! It's funny how your eye can just skate over something like that when you're concentrating on something else.

Control ends up in the .catch with a JSON error, exactly as you said. But, hey, all isn't lost as it's easy enough to pick up response.status in the first .then() and redirect as in your try block.

As you say, it's all a matter of style but, to me, try/catch blocks always look a bit desperate!

I like your boiler-plate examples. I'll make a note of the abort template.

Regards, MJ