0
function postFetch(data) {
  document.getElementById('test').innerHTML = data.name;
}

//fetch("test").then(data=>data.json()).then(res=>{postFetch(res)});
fetch("test").then(data => postFetch(data.json()))

test is a json file with {"name":"Carla"} in it. And i have a html page with a element with id test in it, that sources this script. As it is, the page displays undefined. However, if i switch the uncomment the commented line and comment the next, it displays the intended Carla on the page. Why don't they behave the same?

  • 3
    `.json()` returns a `Promise`: _"The [`json()`](https://developer.mozilla.org/en-US/docs/Web/API/Response/json) method of the `Response` interface takes a `Response` stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON. "_ – Andreas Oct 02 '21 at 13:10
  • 1
    ...and so `data` in `postFetch` is a promise (and promises don't have a `name` property, so `.name` is `undefined`. You have to hook into the fulfillment of the promise to get its fulfillment value. Side note: You also need to check whether the HTTP request worked (`fetch` only rejects on *network* errors, not HTTP errors). I've written up more details [here](http://blog.niftysnippets.org/2018/06/common-fetch-errors.html). – T.J. Crowder Oct 02 '21 at 13:11
  • you are not waiting for the json() promise function to get resolved. you are probably passing a Promise to postFetch function – Dev-2019 Oct 02 '21 at 13:16

0 Answers0