首页 > 解决方案 > 无法使用从 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)

标签: javascriptfetch-api

解决方案


首先,您需要删除 first 中的大括号thenrespo => 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);
})


推荐阅读