繁体   English   中英

获取 response.json() 和 response.status

[英]fetch response.json() and response.status

这是使用body.json()并获取状态代码的唯一方法吗?

let status;

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

这不起作用,因为它在响应字段中返回一个承诺:

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

您的状态在第二个then不可见。 您可以在单个then获取这两个属性。

json()向您返回一个新的 Promise,因此您需要在该函数的结果的then内创建您的对象。 如果你从一个函数中返回一个 Promise,它将会被完成并返回完成的结果——在我们的例子中是对象。

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

上周我遇到了完全相同的问题。 .json方法向解析的 JSON 返回一个承诺,而不是解析的 JSON 本身。 如果您想同时访问响应和解析的 JSON,则需要使用嵌套闭包,如下所示:

fetch(url)
    .then(response => {
        response.json().then(parsedJson => {
            // code that can access both here
        })
    });

或者,您可以使用async/await语法:

async function fetchTheThing() {
    const response = await fetch(url);
    const parsedJson = await response.json();

    // code that can access both here
}

当然,你会想要检查错误,要么使用.catch(...)对 Promise 的调用,要么使用带有async函数的try...catch块。 您可以创建一个处理 JSON 和错误情况的函数,然后将其重用于所有提取。 例如,这样的事情:

function fetchHandler(response) {
    if (response.ok) {
        return response.json().then(json => {
            // the status was ok and there is a json body
            return Promise.resolve({json: json, response: response});
        }).catch(err => {
            // the status was ok but there is no json body
            return Promise.resolve({response: response});
        });

    } else {
        return response.json().catch(err => {
            // the status was not ok and there is no json body
            throw new Error(response.statusText);
        }).then(json => {
            // the status was not ok but there is a json body
            throw new Error(json.error.message); // example error message returned by a REST API
        });
    }
}

我不认为这是最好的设计模式,但希望这能阐明 fetch API 的工作原理。

使用两个'then's 对我来说似乎没有必要。

async/await 可以很容易地完成工作。

    fetch('http://test.com/getData')
      .then( async (response) => {

        // get json response here
        let data = await response.json();
        
        if(response.status === 200){
         // Process data here
        }else{
         // Rest of status codes (400,500,303), can be handled here appropriately
        }

      })
      .catch((err) => {
          console.log(err);
      })

你试过这个吗?

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

我认为最干净的方法是用你需要的部分创建一个 Promise.all() 。

.then(response => Promise.all([Promise.resolve(response.ok), response.text()]))

哪个可以写得更短

.then(response => Promise.all([response.ok, response.text()]))

承诺返回一个包含所有结果的数组

.then(data => ({ status: data[0], response: data[1] }))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM