获取response.json()和response.status

Guy*_*Guy 18 javascript fetch promise

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

let status;

return fetch(url)
    .then((response => {
         status = response.status;
         return response.json()
     })
    .then(response => {
        return {
            response: response,
            status: status
        }
    });
Run Code Online (Sandbox Code Playgroud)

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

.then((response)=> {return {response: response.json(), status: response.status}})
Run Code Online (Sandbox Code Playgroud)

Sur*_*yan 43

您的状态在第二个中不可见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));
Run Code Online (Sandbox Code Playgroud)

  • 亲爱的主啊,ajax 做得更好 (2认同)

Dom*_*ino 9

上周,我面临着完全相同的问题。该.json方法返回对JSON的承诺,而不是JSON本身。如果要一次访问响应和JSON,则需要使用嵌套的闭包,如下所示:

fetch(...)
    .then(response => {
        response.json().then(json => {
            // code that can access both here
        })
    })
Run Code Online (Sandbox Code Playgroud)

由于传递给jsonpromise的回调是在fetchpromise 的回调内创建的,因此也可以访问response

您可能想要创建一个处理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
        });
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

使用两个 '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);
      })
Run Code Online (Sandbox Code Playgroud)