接口定义
// ./src/type/index.ts
export interface AxiosRequestConfig {
url?: string
method?: Method
data?: any
params?: any
headers?: any
responseType?: XMLHttpRequestResponseType
timeout?: number
transformRequest?: AxiosTransformer | AxiosTransformer[]
transformResponse?: AxiosTransformer | AxiosTransformer[]
cancelToken?: CancelToken
[propName: string]: any
}
//...
export interface CancelToken {
promise: Promise<string>
reason?: string
}
export interface Canceler {
(message?: string): void
}
export interface CancelExecutor {
(cancel: Canceler): void
}
类实现
// ./src/cancel/CancelToken.ts
import { CancelExecutor } from "../types"
interface ResolvePromise {
(reason?: string): void
}
export default class CancelToken {
promise: Promise<string>
reason?: string
constructor(executor: CancelExecutor) {
let resolvePromise: ResolvePromise
this.promise = new Promise<string>(resolve => {
resolvePromise = resolve
})
executor(message => {
if (this.reason) {
return
}
this.reason = message
resolvePromise(this.reason)
})
}
}
使用
// ./src/core/xhr.ts
import { AxiosRequestConfig, AxiosPromise, AxiosResponse } from '../types'
import { parseHeaders } from '../helpers/headers'
import { createError } from '../helpers/error'
export default function xhr(config: AxiosRequestConfig): AxiosPromise {
return new Promise((resolve, reject) => {
const { data = null, url, method = 'get', headers, responseType, timeout, cancelToken } = config
//...
if (cancelToken) {
cancelToken.promise.then(reason => {
request.abort()
reject(reason)
})
}
request.send(data)
//...
})
}