Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

82
Views
Get http response status code after response.json()

I would like to get http status code after response.json to use it in my logic later, can I do something with it?

function apiRequest(path, options) {
    fetch("api/" + path, options)
        .then(response => response.json())
        .then(data => {
            let res = {
                code: 200 //I want to put http status code here,
                data: data
            }

            return res;
        })
}

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

This is slightly tricky using then (as you are currently doing) because you want to get data directly from the response (which is a promise) and some more data from the parsed body (which is another promise).

So you can wrap the status and the data promise in a Promise.all and return that from the first then:

const apiRequest = () => {
  const url = "//swapi.dev/api/planets/1/";
  fetch(url)
    .then((response) => Promise.all([response.status, response.json()]))
    .then(([status, data]) => console.log({status, data}))
}

… but it would be easier to use async/await syntax and ditch the callbacks and you then only have to worry about a single function (and therefore scope) rather than multiple.

const apiRequest = async () => {
  const url = "//swapi.dev/api/planets/1/";
  const response = await fetch(url);
  const data = await response.json();
  const status = response.status;
  console.log({status, data})
}
7 months ago · Juan Pablo Isaza Report

0

As an alternative you could consider async/await. That way you have access to response and data at the same time more easily.

async function apiRequest(path, options) {
    const response = await fetch("api/" + path, options)
    const data = await response.json()

    let res = {
         code: response.status,
         data: data
    }

    // Do something with res
}
7 months ago · Juan Pablo Isaza Report

0

Try this

function apiRequest(path, options) {
    fetch("api/" + path, options)
        .then(response => Promise.all([Promise.resolve(response.status), response.json()]))
        .then(([status, data]) => {
            let res = {
                code: status //I want to put http status code here,
                data: data
            }

            return res;
        })
}

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.