cancellableFetch
创建一个可以随时取消的网络请求,使用 AbortController 实现取消功能。
前置依赖
依赖参数
| 参数名 | 类型 | 说明 |
|---|---|---|
deps.fetch | FetchFunction | Fetch API 函数 |
deps.AbortController | typeof AbortController | AbortController 构造函数 |
环境要求
- 浏览器环境: 需要支持
fetch和AbortControllerAPI(现代浏览器均支持)
函数签名
typescript
function cancellableFetch(
input: RequestInfo | URL,
init?: RequestInit,
deps: CancellableFetchDeps
): CancellableFetchResult
interface CancellableFetchDeps {
fetch: FetchFunction
AbortController: typeof AbortController
}
interface CancellableFetchResult {
promise: Promise<Response>
cancel: (reason?: any) => void
signal: AbortSignal
}参数
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
input | RequestInfo | URL | 是 | 请求 URL 或 Request 对象 |
init | RequestInit | 否 | 请求配置选项(会自动添加 signal) |
deps.fetch | FetchFunction | 是 | Fetch API 函数 |
deps.AbortController | typeof AbortController | 是 | AbortController 构造函数 |
返回值
| 类型 | 说明 |
|---|---|
CancellableFetchResult | 包含 promise、cancel 方法和 signal 的对象 |
CancellableFetchResult 属性
| 属性名 | 类型 | 说明 |
|---|---|---|
promise | Promise<Response> | 请求的 Promise |
cancel | (reason?: any) => void | 取消请求的方法 |
signal | AbortSignal | 取消信号对象 |
工作原理
创建 AbortController:
- 使用传入的
AbortController构造函数创建控制器 - 获取
AbortSignal信号对象
- 使用传入的
合并请求配置:
- 如果用户提供了自定义
signal,则使用用户的signal - 否则使用新创建的
signal - 将
signal添加到请求配置中
- 如果用户提供了自定义
发起请求:
- 使用
fetch函数发起网络请求 - 返回包含
promise、cancel方法和signal的对象
- 使用
取消请求:
- 调用
cancel()方法会触发AbortController.abort() fetch会检测到signal被中止,抛出AbortError- Promise 会 reject,错误类型为
DOMException,名称为AbortError
- 调用
注意事项:
- 如果用户提供了自定义
signal,cancel()方法不会生效(因为无法控制用户的AbortController) cancel()方法具有幂等性,可以多次调用而不会报错- 取消后的 Promise 会 reject,需要使用
catch处理错误 - 应该区分
AbortError(取消)和网络错误