javascript - 如何使用 fetch() api 的响应
问题描述
如何使用来自 fetch api 的响应?
我尝试return
我的回应,但是当我尝试在我的函数中打印这个值时,我得到undefined
,有人可以告诉我如何在不同的函数中使用这个响应吗?
我的响应是嵌套对象的 json
async fetchData() {
const url = `...`;
fetch(url, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
//
})
}).then((response) => response.json())
.then(response => {;
console.log(response) //correct response
return response;
})
}
async getDataFromFetchApi() {
const data= await this.fetchData();
console.log(data); // undefined
if(data != undefined){
throw new BadRequestException();
}
return data;
}
谢谢你的帮助
解决方案
归根结底,async
函数必须return
保证能够正常工作。fetchData
没有返回值。位于return response
a 内部,.then
不适用于fetchData
函数本身。
对于上面的代码,最少的修改就是return fetch(...)
在你的fetchData
函数中,像这样:
async fetchData() {
const url = `...`;
return fetch(/* ... */)
.then((response) => response.json())
.then(response => {
console.log(response) //correct response
return response;
})
}
或者,您可以尽其所能使用async/await
语法,并摆脱您.then
的 s,如下所示:
async fetchData() {
const url = `...`;
const resp = await fetch(/* ... */);
const json = await resp.json();
console.log(json);
return json;
}
推荐阅读
- python - 尝试仅在 tkinter GUI 中水平移动(而不是垂直移动)时冻结标签
- r - 在 R 中编辑数据表中的文本字符串
- php - 为什么 PHP number_format() 改变数字?
- php - 如何创建一个仅与 expo react 本机应用程序连接的 json php api?
- javascript - Promise.all 并等待所有错误
- javascript - 如何禁用输入按下
- sweetalert2 - sweetalet2 commonJS 基本示例
- image - 404 在 Safari 上,但在 Chrome 中使用图像时很好
- javascript - 在反应应用程序中使用符号时出错
- java - Java:使用三元检查setter中的null