gpt4 book ai didi

javascript - 返回对象内的 fetch .json。

转载 作者:行者123 更新时间:2023-12-01 02:27:02 25 4
gpt4 key购买 nike

我有一个API调用函数,我想将response.json()内容以及response.status一起返回到单个对象中。

像这样:

  const getData = data => {
return fetch('/api_endpoint',{
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
.then(response => {
return {
body: response.json(),
status: response.status
}
})
}

问题是response.json()是一个 promise ,所以在它解决之前我无法提取它的值。

我可以通过这样做来破解它:

  const getData = data => {
let statusRes = undefined;
return fetch('/api_endpoint',{
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
.then(response => {
statusRes = response.status;
return response.json()
})
.then(data => {
return {
body: data,
status: statusRes
}
}
)
}

但感觉不对。有人有更好的主意吗?

最佳答案

const getData = data => {
return fetch('/api_endpoint',{
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
.then(async response => {
return {
body: await response.json(),
status: response.status
}
})
}
es6 async/await可能会让它看起来更干净

关于javascript - 返回对象内的 fetch .json。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48676998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com