Today I Learned

hashrocket A Hashrocket project

Get the response json with `fetch` and `Promises`

The fetch api is intertwined with the Promise api. The fetch function itself returns a Promise. The success function for that promise will have an argument that is a Response object.

fetch('myResource.json').then(function(response) {
  console.log('This is a response object', response);
})

The Response object implements Body which has several properties and several methods that help you to access the contents of the body of the response.

Body.json() is a function that reads the response stream to completion and parses the response as json. This operation may take take time, so instead of just returning the json, it returns another Promise. The success function of this promise will have the resulting json as an argument.

fetch('myResource.json').then(function(response) {
  response.json().then(function(parsedJson) {
    console.log('This is the parsed json', parsedJson);
  })
})

Of course, if you return a promise from a success function, then that promise will be resolved in the next chained then function.

fetch('myResource.json').then(function(response) {
  return response.json();
}).then(function(parsedJson) {
  console.log('This is the parsed json', parsedJson);
})
See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.