使axios直接返回响应而不是AxiosResponse包装器?

时间:2019-05-09 14:21:29

标签: javascript typescript axios

我们可以让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');

2 个答案:

答案 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();