Javascript 获取 response.json() 和 response.status
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47267221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fetch response.json() and response.status
提问by Guy
Is this the only way to use the body.json()and also get the status code?
这是使用body.json()并获取状态代码的唯一方法吗?
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}})
回答by Suren Srapyan
Your status is not visible in the second then. You can just get the two properties in the single then.
您的状态在第二个中不可见then。您可以在单个then.
json()returns a new Promise to you, so you need to create your object inside the thenof 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.
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));
回答by Domino
I was faced with the exact same problem last week. The .jsonmethod returns a promise to the JSON, not the JSON itself. If you want to access both the response and the JSON at once, you'll need to use nested closures like this:
上周我遇到了完全相同的问题。该.json方法向 JSON 返回一个承诺,而不是 JSON 本身。如果您想同时访问响应和 JSON,则需要使用嵌套闭包,如下所示:
fetch(...)
.then(response => {
response.json().then(json => {
// code that can access both here
})
})
Since the callback passed to the jsonpromise was created within the callback to the fetchpromise, it'll have access to the responseas well.
由于传递给jsonPromise 的回调是在对 Promise 的回调中创建的fetch,因此它也可以访问response。
You might want to make a function that handles JSON and error cases, and then reuse it for all your fetches. For example, something like this:
您可能想要创建一个处理 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
});
}
}
回答by Drag13
Did you try this?
你试过这个吗?
return fetch(url)
.then((r)=> {return {response: r.json(), status: r.status}})
回答by blindguy
I think the cleanest way is to create a Promise.all() with the pieces you need.
我认为最干净的方法是用你需要的部分创建一个 Promise.all() 。
.then(response => Promise.all([Promise.resolve(response.ok), response.text()]))
.then(response => Promise.all([Promise.resolve(response.ok), response.text()]))
Which can be written shorter as
哪个可以写得更短
.then(response => Promise.all([response.ok, response.text()]))
.then(response => Promise.all([response.ok, response.text()]))
The promise returns an array with all of the results
承诺返回一个包含所有结果的数组
.then(data => ({ status: data[0], response: data[1] }))
.then(data => ({ status: data[0], response: data[1] }))

