2

I see alot of examples online it goes:

 fetch(url)
  .then((resp) => resp.json()) // Transform the data into json
  .then(function(obj) {
    // do stuff
    })
  })

Why not just:

fetch(url)
  .then(function(data) {
       var obj = data.json();
       // do stuff
    })
  })

Why is another "then" required... or is it required?

Shai UI
  • 50,568
  • 73
  • 204
  • 309
  • not a duplicate, I don't even understand that question you commented. My question is alot simpler. – Shai UI Mar 31 '18 at 19:52
  • `fetch` require a second `then` because in the first respanse the server is just letting you know that your request went through just fine. – Abslen Char Mar 31 '18 at 19:55
  • Wouldn't you need to wait for the json to be returned from the url before doing stuff? If you don't double chain the then wouldn't it result in trying to do stuff some times before the json is returned, since you get a success for the fetch only. – Josh Adams Mar 31 '18 at 19:55
  • Its because the response we get is an object with several methods that we can choose from. **These methods return a promise**. That's why we use the second then. `.json` is just one of them. It begins with reading headers and status before the actual response reaches. So we have to wait for full response. – kimobrian254 Mar 31 '18 at 20:07
  • @finch ok, so .json() returns a promise. isn't there a .jsonWithoutPromise() or something? I don't like that extra then. – Shai UI Mar 31 '18 at 20:12
  • 1
    The reason it returns a promise is because it's like a stream, it starts reading response status then headers etc. Using .json returns a promise for the actual body that's yet to arrive. So if you accessed it immediately, there would be no data. – kimobrian254 Mar 31 '18 at 20:16
  • You can always check to confirm if the response is ok with: `fetch(api) .then(res => res.ok ? res : res.json().then(err => Promise.reject(err)));` – kimobrian254 Mar 31 '18 at 20:18

0 Answers0