import type { AxiosRequestConfig, Canceler } from 'axios'; import axios from 'axios'; import { isFunction } from '/@/utils/is'; // Used to store the identification and cancellation function of each request let pendingMap = new Map<string, Canceler>(); export const getPendingUrl = (config: AxiosRequestConfig) => [config.method, config.url].join('&'); export class AxiosCanceler { /** * Add request * @param {Object} config */ addPending(config: AxiosRequestConfig) { this.removePending(config); const url = getPendingUrl(config); config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => { if (!pendingMap.has(url)) { // If there is no current request in pending, add it pendingMap.set(url, cancel); } }); } /** * @description: Clear all pending */ removeAllPending() { pendingMap.forEach((cancel) => { cancel && isFunction(cancel) && cancel(); }); pendingMap.clear(); } /** * Removal request * @param {Object} config */ removePending(config: AxiosRequestConfig) { const url = getPendingUrl(config); if (pendingMap.has(url)) { // If there is a current request identifier in pending, // the current request needs to be cancelled and removed const cancel = pendingMap.get(url); cancel && cancel(url); pendingMap.delete(url); } } /** * @description: reset */ reset(): void { pendingMap = new Map<string, Canceler>(); } } 这是做什么的

时间: 2024-04-18 20:27:58 浏览: 20
这段代码是一个用于管理取消 Axios 请求的辅助工具类。它包含了以下功能: 1. `addPending(config: AxiosRequestConfig)`: 添加请求到待取消列表中。它会根据请求的方法和 URL 生成一个唯一的标识,并将该标识和取消函数存储在 `pendingMap` 中。 2. `removeAllPending()`: 清除所有待取消的请求。它会遍历 `pendingMap` 中的所有取消函数,并执行它们,然后清空 `pendingMap`。 3. `removePending(config: AxiosRequestConfig)`: 从待取消列表中移除指定的请求。它会根据请求的方法和 URL 生成标识,并从 `pendingMap` 中获取对应的取消函数,然后执行该函数并将其从 `pendingMap` 中删除。 4. `reset()`: 重置待取消列表。它会将 `pendingMap` 重置为空的 Map。 这个工具类的主要作用是在发送请求之前添加请求到待取消列表中,然后根据需要进行取消或清除请求。这在处理页面跳转或组件卸载时非常有用,可以避免因为未完成的请求导致的问题。
相关问题

axios-miniprogram Canceler 应如何导入

要在小程序中使用 `axios-miniprogram` 的 `Canceler` 类,需要先安装 `axios-miniprogram` 包。可以使用以下命令进行安装: ``` npm install axios-miniprogram --save ``` 然后,在需要使用 `Canceler` 的地方,可以按照以下方式导入: ```javascript import { Canceler } from 'axios-miniprogram'; ``` 然后就可以使用 `Canceler` 类来创建一个取消请求的对象。例如: ```javascript const cancelToken = axios.CancelToken; const canceler = new cancelToken.source(); ``` 这里的 `cancelToken` 是 `axios-miniprogram` 中的一个工厂函数,用于创建 `CancelToken` 类的实例。`canceler` 则是一个 `CancelToken` 类的实例,用于创建取消请求的对象。

基于TypeScript从零重构axios

好的,让我们开始重构axios! 首先,我们需要安装TypeScript和相关的依赖。运行以下命令: ``` npm install typescript @types/node @types/qs @types/form-data ``` 接下来,我们需要创建一个tsconfig.json文件。在项目根目录下创建一个名为tsconfig.json的文件,并将以下内容复制到其中: ```json { "compilerOptions": { "lib": ["es6", "dom"], "target": "es5", "module": "commonjs", "moduleResolution": "node", "declaration": true, "sourceMap": true, "outDir": "./dist", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "exclude": ["node_modules"] } ``` 现在,我们可以开始重构axios的代码了。 首先,我们需要将axios的代码转换为TypeScript。我们可以将所有的JavaScript文件重命名为.ts文件,并使用TypeScript的语法更新代码。例如,我们可以使用类型注释来定义函数的参数类型和返回类型。 下面是一个使用TypeScript语法重构的示例: ```typescript import * as http from 'http'; import * as https from 'https'; import * as url from 'url'; import * as zlib from 'zlib'; import { Cancel, CancelToken } from './cancel'; import { isFormData } from './utils'; import settle from './core/settle'; import buildURL from './helpers/buildURL'; import parseHeaders from './helpers/parseHeaders'; import createError from './core/createError'; import enhanceError from './core/enhanceError'; import defaults from './defaults'; interface AxiosRequestConfig { url?: string; method?: string; baseURL?: string; headers?: any; params?: any; data?: any; timeout?: number; withCredentials?: boolean; responseType?: XMLHttpRequestResponseType; xsrfCookieName?: string; xsrfHeaderName?: string; onDownloadProgress?: (progressEvent: any) => void; onUploadProgress?: (progressEvent: any) => void; cancelToken?: CancelToken; } interface AxiosResponse<T = any> { data: T; status: number; statusText: string; headers: any; config: AxiosRequestConfig; request?: any; } interface AxiosError<T = any> extends Error { config: AxiosRequestConfig; code?: string; request?: any; response?: AxiosResponse<T>; isAxiosError: boolean; } interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {} interface Axios { defaults: AxiosRequestConfig; interceptors: { request: AxiosInterceptorManager<AxiosRequestConfig>; response: AxiosInterceptorManager<AxiosResponse>; }; request<T = any>(config: AxiosRequestConfig): AxiosPromise<T>; get<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; delete<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; head<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; options<T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>; put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>; patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): AxiosPromise<T>; } interface AxiosInstance extends Axios { <T = any>(config: AxiosRequestConfig): AxiosPromise<T>; <T = any>(url: string, config?: AxiosRequestConfig): AxiosPromise<T>; } interface AxiosStatic extends AxiosInstance { create(config?: AxiosRequestConfig): AxiosInstance; CancelToken: CancelTokenStatic; Cancel: CancelStatic; isCancel: (value: any) => boolean; } interface AxiosInterceptorManager<T> { use(resolved: ResolvedFn<T>, rejected?: RejectedFn): number; eject(id: number): void; } interface ResolvedFn<T> { (val: T): T | Promise<T>; } interface RejectedFn { (error: any): any; } interface CancelToken { promise: Promise<Cancel>; reason?: Cancel; throwIfRequested(): void; } interface Canceler { (message?: string): void; } interface CancelExecutor { (cancel: Canceler): void; } interface CancelTokenSource { token: CancelToken; cancel: Canceler; } interface CancelTokenStatic { new (executor: CancelExecutor): CancelToken; source(): CancelTokenSource; } interface Cancel { message?: string; } interface CancelStatic { new (message?: string): Cancel; } function axios<T = any>(config: AxiosRequestConfig): AxiosPromise<T> { return dispatchRequest(config); } function createInstance(config: AxiosRequestConfig): AxiosInstance { const context = new Axios(config); const instance = Axios.prototype.request.bind(context); Object.assign(instance, Axios.prototype, context); return instance as AxiosInstance; } const axiosInstance = createInstance(defaults); axiosInstance.create = function create(config) { return createInstance(Object.assign(defaults, config)); }; function getDefaultAdapter() { let adapter; if (typeof XMLHttpRequest !== 'undefined') { adapter = require('./adapters/xhr'); } else if (typeof http !== 'undefined') { adapter = require('./adapters/http'); } else if (typeof https !== 'undefined') { adapter = require('./adapters/http'); } return adapter; } function dispatchRequest<T = any>(config: AxiosRequestConfig): AxiosPromise<T> { throwIfCancellationRequested(config.cancelToken); processConfig(config); return getDefaultAdapter()(config).then((response) => { return transformResponseData(response); }, (error) => { if (error && error.response) { error.response = transformResponseData(error.response); } return Promise.reject(error); }).then((response) => { settle(resolve, reject, response); return response; }, (error) => { settle(resolve, reject, enhanceError(error)); return Promise.reject(enhanceError(error)); }); } function processConfig(config: AxiosRequestConfig): void { config.url = transformURL(config); config.headers = transformHeaders(config); config.data = transformData(config); config.params = transformParams(config); } function transformURL(config: AxiosRequestConfig): string { const { url, params, baseURL } = config; return buildURL(url!, params, baseURL); } function transformHeaders(config: AxiosRequestConfig): any { const { headers = {}, data } = config; return Object.assign(headers.common || {}, headers[config.method!] || {}, headers, data ? data.headers : null); } function transformData(config: AxiosRequestConfig): any { const { data } = config; return isFormData(data) ? data : JSON.stringify(data); } function transformParams(config: AxiosRequestConfig): any { const { params } = config; return params ? params : null; } function transformResponseData(response: AxiosResponse): AxiosResponse { response.data = transformData(response); response.headers = parseHeaders(response.headers, response.config); response.data = transformData(response); return response; } function throwIfCancellationRequested(cancelToken?: CancelToken): void { if (cancelToken) { cancelToken.throwIfRequested(); } } export default axiosInstance; ``` 现在我们已经将axios的代码转换为了TypeScript,接下来我们需要更新一下项目的结构。 我们可以将所有的TypeScript代码放在一个src目录下,并将编译后的JavaScript代码放在一个dist目录下。这样做可以使我们的代码更加结构化和易于管理。 接下来,我们需要更新package.json文件中的scripts字段,以便使用TypeScript编译我们的代码。在scripts字段中添加以下内容: ```json "scripts": { "build": "tsc" } ``` 现在我们可以运行npm run build命令来编译我们的代码了。 最后,我们需要更新我们的引用代码,以便使用重构后的axios。例如,我们可以使用以下代码来发送一个GET请求: ```typescript import axios from './dist/axios'; axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` 这就是使用TypeScript从零重构axios的过程。

相关推荐

import axios from 'axios' import type { CancelTokenStatic, AxiosRequestConfig, AxiosInstance, AxiosError, InternalAxiosRequestConfig, AxiosResponse, CancelTokenSource } from 'axios' import { useGlobalStore } from '@/stores' import { hasOwn, hasOwnDefault } from '@/utils' import { ElMessage } from 'element-plus' /** * @description: 请求配置 * @param {extendHeaders} {[key: string]: string} 扩展请求头用于不满足默认的 Content-Type、token 请求头的情况 * @param {ignoreLoading} boolean 是否忽略 loading 默认 false * @param {token} boolean 是否携带 token 默认 true * @param {ignoreCR} boolean 是否取消请求 默认 false * @param {ignoreCRMsg} string 取消请求的提示信息 默认 Request canceled * @param {contentType} $ContentType 重新定义 Content-Type 默认 json * @param {baseURL} $baseURL baseURL 默认 horizon * @param {timeout} number 超时时间 默认 10000 * @return {_AxiosRequestConfig} **/ interface _AxiosRequestConfig extends AxiosRequestConfig { extendHeaders?: { [key: string]: string } ignoreLoading?: boolean token?: boolean ignoreCR?: boolean ignoreCRMsg?: string } enum ContentType { html = 'text/html', text = 'text/plain', file = 'multipart/form-data', json = 'application/json', form = 'application/x-www-form-urlencoded', stream = 'application/octet-stream', } const Request: AxiosInstance = axios.create() const CancelToken: CancelTokenStatic = axios.CancelToken const source: CancelTokenSource = CancelToken.source() const globalStore = useGlobalStore() Request.interceptors.request.use( (config: InternalAxiosRequestConfig) => { globalStore.setGlobalState('loading', !hasOwnDefault(config, 'ignoreLoading', true)) config.baseURL = hasOwnDefault(config, 'baseURL', '/api') config.headers = { ...config.headers, ...{ 'Content-Type': ContentType[hasOwnDefault(config, 'Content-Type', 'json')], }, ...hasOwnDefault(config, 'extendHeaders', {}), } hasOwnDefault(config, 'token', true) && (config.headers.token = globalStore.token) config.data = config.data || {} config.params = config.params || {} config.timeout = hasOwnDefault(config, 'timeout', 10000) config.cancelToken = source.token config.withCredentials = true hasOwnDefault(config, 'ignoreCR', false) && source.cancel(hasOwnDefault(config, 'ignoreCRMsg', 'Request canceled')) return config }, (error: AxiosError) => { return Promise.reject(error) } ) Request.interceptors.response.use( (response: AxiosResponse) => { globalStore.setGlobalState('loading', false) const { data, status } = response let obj = { ...data } if (!hasOwn(data, 'status')) obj.status = status return obj }, (error: AxiosError) => { globalStore.setGlobalState('loading', false) ElMessage.error(error.message) return Promise.reject(error) } ) export default (config?: _AxiosRequestConfig) => Request(config) 修改代码,使其能够批量取消请求

最新推荐

recommend-type

VB学生档案管理系统设计与实现.rar

计算机专业毕业设计VB精品论文资源
recommend-type

debugpy-1.6.3-cp37-cp37m-win_amd64.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

基于ssm的学生宿舍报修管理系统

开发语言:Java JDK版本:JDK1.8(或11) 服务器:tomcat 数据库:mysql 5.6/5.7(或8.0) 数据库工具:Navicat 开发软件:idea 依赖管理包:Maven 代码+数据库保证完整可用,可提供远程调试并指导运行服务(额外付费)~ 如果对系统的中的某些部分感到不合适可提供修改服务,比如题目、界面、功能等等... 声明: 1.项目已经调试过,完美运行 2.需要远程帮忙部署项目,需要额外付费 3.本项目有演示视频,如果需要观看,请联系我v:19306446185 4.调试过程中可帮忙安装IDEA,eclipse,MySQL,JDK,Tomcat等软件 重点: 需要其他Java源码联系我,更多源码任你选,你想要的源码我都有! https://img-blog.csdnimg.cn/direct/e73dc0ac8d27434b86d886db5a438c71.jpeg
recommend-type

cryptography-42.0.1-cp37-abi3-musllinux_1_1_x86_64.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

sja1300.x86_64.tar.gz

SQLyong 各个版本,免费下载 SQLyog是业界著名的Webyog公司出品的一款简洁高效、功能强大的图形化MySQL数据库管理工具。使用SQLyog可以快速直观地让您从世界的任何角落通过网络来维护远端的MySQL数据库。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

用Spring boot和vue写一个登录注册界面

好的,这是一个比较常见的技术问题,我可以为您提供一些参考资料和思路。首先,您可以使用Spring Boot作为后端框架来处理用户认证和注册的逻辑,比如使用Spring Security实现用户登录认证。同时,您还需要设计相应的数据模型和数据库表结构来存储用户信息。在前端方面,您可以使用Vue.js作为框架来构建登录注册页面,使用Axios来发起API请求并和后端进行交互。当然,在实现过程中,还需要考虑一些具体细节,比如数据校验、安全性和用户体验等方面。希望这些信息能够帮助到您。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。