javascript - 无法使用从 Fetch API 返回的数据
问题描述
我正在尝试使用 fetch 从此 API 获取数据,并且我知道返回了一个未决的承诺,但它没有自行解决,因此我无法使用数据。我不知道我做错了什么。
function api () {
return fetch('https://api.punkapi.com/v2/beers').then(respo => { respo.json() } ).then(data => {
const beersData = data;
return beersData;
}).catch(error => {
console.error(error)
}) ;
}
api();
console.log(beersData)
解决方案
首先,您需要删除 first 中的大括号then
。
respo => respo.json()
相当于respo => { return respo.json() }
。
其次,你需要在调用api
函数时处理 Promise,因为它api()
也会返回 Promise。
function api () {
return fetch('https://api.punkapi.com/v2/beers')
.then(respo => respo.json())
.then(data => {
const beersData = data;
return beersData;
}).catch(error => {
console.error(error)
}) ;
}
api()
.then(res => {
console.log(res);
})
推荐阅读
- python - Python 网页抓取,使用 html-requests 查找特定元素并提取文本
- c++ - ZED 相机:未定义对 sl::string::string() 的引用
- angular - 路由中 loadChildren 的 Angular 11 问题
- r - 使用 str_extract 提取 R 中字符串中最后一次出现模式的时间
- python - 为什么 PIL 无法加载我的图像?错误:图像数据不足
- php - 仅在 WooCommerce 产品简短描述中为客人显示自定义文本
- python-3.x - 如何优化python3中的嵌套循环?
- trustpilot - 授权类型:授权代码 ERR:需要客户端标识符
- python-3.x - 根据键值熊猫拆分数据框列
- mysql - MySQL:根据与字段匹配的值列表,每行选择一个结果,即使没有匹配,并且列表包括重复项