javascriptpromisefetch-api

fetch response.json() and response.status


Is this the only way to use the body.json() and also get the status code?

let status;

return fetch(url)
    .then(response => {
         status = response.status;
         return response.json()
     })
    .then(response => {
        return {
            response: response,
            status: status
        }
    });

This doesn't work as it returns a promise in the response field:

.then((response)=> {return {response: response.json(), status: response.status}})

Solution

  • Your status is not visible in the second then. You can just get the two properties in the single then.

    json() returns a new Promise to you, so you need to create your object inside the then of the result of that function. If you return a Promise from a function, it will be fulfilled and will return the result of the fulfillment - in our case the object.

    fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(r =>  r.json().then(data => ({status: r.status, body: data})))
    .then(obj => console.log(obj));