-1

I am trying to do the following in ES6 JavaScript, but can't figure out the right syntax. The second .then() works well, but the first one, which should throw an error doesn't (the first part contains standard JS syntax)

 return fetch('/api/data.json', {
        credentials: 'same-origin'
     }).then(function(response) {
       if (!response.ok) {
         throw Error(response.statusText);
       }
       return response;
       })
       .then(response => response.json())
       ................
4
  • Could you provide a fiddle? Commented Mar 15, 2016 at 13:57
  • Why these two thens? Commented Mar 15, 2016 at 13:58
  • How would introducing an arrow affect the behavior you're seeing though? The code you've posted looks fine. Unless you're expecting an Error to be thrown of course - because it won't, you need to add a .catch at the end to trap that error Commented Mar 15, 2016 at 16:13
  • it doesn't affect the result, but the code is written in arrow-style, so it looks better like this. Commented Mar 18, 2016 at 15:26

2 Answers 2

2

There is no "magic" :) about it

   .then(response => {
     if (!response.ok) {
       throw Error(response.statusText);
     }
     return response;
   })
Sign up to request clarification or add additional context in comments.

1 Comment

nice, thank you! I think I must have a typo in my code when I've tried :)
-2

You can do this for first .then():

.then(response => !response.ok ? throw Error() : response)

1 Comment

This is invalid JavsScript. throw is a statement, not an expression.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.