Jesvin Jose
Jesvin Jose

Reputation: 23078

How to get json and response status in a single callback with fetch?

I want to get the json content, status and other response attributes in a single callback.I cannot go much further than example code:

fetch('/users.json')
  .then(function(response) {
    console.log(response.status)
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  })

I can print the status, but trying to return both response status and json in the first callback leads to the second callback getting a Promise, which I think is square one!

How do I get json as well as other attributes in a single callback?

Upvotes: 2

Views: 52

Answers (1)

GPicazo
GPicazo

Reputation: 6676

Try this:

.fetch('/users.json')
  .then(function(response) {
    return {
      status: response.status,
      data: response.json()
    };
  }).then(function(result) {
    console.log('parsed json', result.data);
    console.log('status', result.status);
  });

Upvotes: 1

Related Questions