axios请求并发数改造

63 阅读1分钟
import {  InternalAxiosRequestConfig } from 'axios'

/**
 * 请求接口队列
*/
type Queue = {
	config: InternalAxiosRequestConfig;
	resolve: (value: InternalAxiosRequestConfig | PromiseLike<InternalAxiosRequestConfig>) => void;
}

export default class AxiosQueue {
  
  /**
 * 等待的队列
*/
 waitQueue: Queue[] = [];

/**
 * 执行的队列
*/
 runQueue: Queue[] = [];

/**
 * 限制执行队列的最大长度
*/

 LIMIT_QUEUE: number = 6;
 
 /**
	* 自定义请求个数
 */
 constructor (LIMIT_QUEUE: number) {
	this.LIMIT_QUEUE = LIMIT_QUEUE
 }

	/**
	 * 运行执行队列
	*/
	public doRunQueue() {
		if (this.runQueue.length < this.LIMIT_QUEUE && this.waitQueue.length) {
			const doingRequest = this.waitQueue.shift();
			doingRequest?.resolve(doingRequest.config)
			if(doingRequest) this.runQueue.push(doingRequest)
		}
	}
	/**
	 * 返回失败或成功后的处理
	*/
	public handleResponse (url?: string) {
		if (!url) return;
		// runQueue队列删除
		const index = this.runQueue.findIndex(queue => queue?.config.url === url)
		this.runQueue.splice(index, 1)
		// 执行下一个队列
		this.doRunQueue()
	}

	public useConfig (config: any) {
		return new Promise(resolve => {
				// 进入等待队列
				this.waitQueue.push({config, resolve})	
				// 执行队列
				this.doRunQueue()
			})
	}
}

##axios请求队列示例

import AxiosQueue from '...'
# limit_num 定义并发限制数 默认写的6const limit_num = 6
const axiosQueue = new AxiosQueue(limit_num)

request.use(
  config => {
    ...,
    return axiosQueue.useConfig(config)
  }
)

response.use(
  response => {
    const { config } = response
    axiosQueue.handleResponse(config.url)
  },
  error => {
    const url = error.config.url
    axiosQueue.handleResponse(url)
  }
)