需求分析

官方 axios 库实现了 axios.all、axios.spread 等方法,它们的用法如下:

  1. function getUserAccount() {
  2. return axios.get('/user/12345');
  3. }
  4. function getUserPermissions() {
  5. return axios.get('/user/12345/permissions');
  6. }
  7. axios.all([getUserAccount(), getUserPermissions()])
  8. .then(axios.spread(function (acct, perms) {
  9. // Both requests are now complete
  10. }));

以上两个方法完全可由 Promose.all替代

官方 axios 库也通过 axios.Axios 对外暴露了 Axios 类(几乎没有使用场景,为了和官方api一致)
另外对于 axios 实例,官网还提供了 getUri 方法在不发送请求的前提下根据传入的配置返回一个 url,如下:

  1. const fakeConfig = {
  2. baseURL: 'https://www.baidu.com/',
  3. url: '/user/12345',
  4. params: {
  5. idClient: 1,
  6. idTest: 2,
  7. testString: 'thisIsATest'
  8. }
  9. }
  10. console.log(axios.getUri(fakeConfig))
  11. // https://www.baidu.com/user/12345?idClient=1&idTest=2&testString=thisIsATest

代码实现

类型声明

  1. export interface Axios {
  2. default: AxiosRequestConfig
  3. interceptors: {
  4. request: AxiosInterceptorManager<AxiosRequestConfig>
  5. response: AxiosInterceptorManager<AxiosResponse>
  6. }
  7. request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>
  8. get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
  9. head<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
  10. delete<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
  11. options<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>
  12. post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
  13. put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
  14. patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>
  15. getUri(config: AxiosRequestConfig): string
  16. }
  17. export interface AxiosStatic extends AxiosInstance {
  18. create(config?: AxiosRequestConfig): AxiosInstance
  19. CancelToken: CancelTokenStatic
  20. Cancel: CancelStatic
  21. isCancel: (val: any) => boolean
  22. // more 扩展静态方法
  23. all<T>(promises: Array<T | Promise<T>>): Promise<T[]>
  24. spread<T, R>(callback: (...args: T[]) => R): (arr: T[]) => R
  25. Axios: AxiosClassStatic
  26. }
  27. export interface AxiosClassStatic {
  28. new(config: AxiosRequestConfig): Axios
  29. }

代码实现

export default class Axios {
  // ...
  getUri(config: AxiosRequestConfig) {
    config = mergeConfig(this.default, config)

    return transformUrl(config)
  }
}
axios.all = function (promises) {
  return Promise.all(promises)
}
axios.spread = function (callback) {
  return function (args) {
    return callback.apply(null, args)
  }
}
axios.Axios = Axios