【发布时间】:2021-06-03 12:31:00
【问题描述】:
我正在尝试使用 fetch 从 API 中获取数据,我可以 console.log 将结果记录在 fetch 中,但在 fetch 之外我无法访问数据。
所以我得到了这个包含函数的 fetchData.js 文件:
export const fetchData = (url) => {
return fetch(url)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error))
}
然后在 app.jsx 文件中我这样调用函数:
import { fetchData } from "./fetchData";
const URL = "https://pokeapi.co/api/v2/pokemon"
function App() {
let data = fetchData(URL);
console.log(data);
//return etc
但是 console.log(data) 一直说“未定义”
有人可以帮帮我吗?
【问题讨论】:
-
你正在调用一个异步函数,然后在检查它的值之前没有等待它返回。
-
没错,但他应该在日志中看到
Promise。尝试删除第二个then,即.then(result => console.log(result))。它正在返回undefined
标签: javascript reactjs api promise fetch