无法使用从 Fetch API 返回的数据
Can't use data returned from 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)
首先,您需要删除第一个 then
中的大括号。
respo => respo.json()
等价于 respo => { return respo.json() }
.
其次,您需要在调用 api
函数时处理 promise,因为 api()
也 returns 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);
})
我正在尝试使用 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)
首先,您需要删除第一个 then
中的大括号。
respo => respo.json()
等价于 respo => { return respo.json() }
.
其次,您需要在调用 api
函数时处理 promise,因为 api()
也 returns 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);
})