我们可以让axios
直接返回Puppy[]
而不是AxiosResponse<Puppy[]>
并获得.then(response => response.data)
吗?
const fetchKittens = (): Promise<Kitten[]> => axios.get<Kitten[]>('/kittens')
.then(response => response.data);
// axios magic
const fetchPuppies = (): Promise<Puppy[]> => axios.get<Puppy[]>('/puppies');
答案 0 :(得分:0)
不。 Axios请求方法始终返回承诺。无法进行同步HTTP请求(这会降低性能)。
答案 1 :(得分:0)
创建一个包装函数,该函数将调用一个请求并仅返回data
const wrapAxiosResponse = async <T>(
action: ReturnType<typeof axios.get> | ReturnType<typeof axios.post> // type of your request list
): Promise<T> => {
let response = await action;
return response.data as T;
}
使用方法
const fetchKittens = (): Promise<Kitten[]> => wrapAxiosResponse(axios.get('/kittens'));
然后
fetchKittens().then(data => console.log(data)); // data relates to `response.data`
或async/await
系统税
const data = await fetchKittens();