我正在尝试使用以下代码获取数据:
export const genres =()=>{
const apiUrl = "http://localhost:3000/api";
fetch(apiUrl + "/genres")
.then(response => response.json())
.then(data => {
const res = data.results
return res
})
}
那么我想用这段代码来结果
export function getGenres() {
return genres.filter(g => g);
}
但我明白了:TypeError:genres.filter不是一个函数。
我的错误是什么以及如何解决?
谢谢
首先,类型不是数组,而是函数,因此不会在其上定义过滤器
其次,流派目前没有返回任何东西
第三,类型是一种异步方法,所以你需要处理promises.You可以使用异步等待它
export const genres =()=>{
const apiUrl = "http://localhost:3000/api";
return fetch(apiUrl + "/genres")
.then(response => response.json())
.then(data => {
const res = data.results
return res
})
}
export async function getGenres() {
try {
const res = await genres();
return res.filter(g => g);
} catch(e) {
console.log('err', e);
}
}
genres
是一个函数,所以你不能直接使用filter
。
您可以调用genres
函数并返回fetch
承诺并等待它解决,然后才能对res
做任何事情。
export const genres = () => {
const apiUrl = "http://localhost:3000/api";
return fetch(apiUrl + "/genres")
.then(response => response.json())
.then(data => {
const res = data.results;
return res;
});
};
export function getGenres() {
return genres().then(res => res.filter(g => g));
}