js需要同时发起百条以上接口请求怎么办?通过Promise实现分批发起并处理接口请求

72
发布时间:2024-07-28 14:19:37

在实际工作中,确实会遇到一些特定的需求促使我们开发出相应的功能。比如,在一个项目中,我曾遇到这样一个场景:有一个接口用于获取列表数据,而列表中的每一项都包含一个需要通过额外的单独请求来填充的属性。这种需求往往能催生出一些实用的技术解决方案。

在这个过程中,有几点值得注意:当进行批量请求时,除了要考虑如何合理地分批处理外,还需要关注如何适当地取消未完成的任务以及如何继续之前已有的任务。例如,如果用户在一个页面上触发了大量数据的请求(比如说一百条),但这些请求尚未全部完成时用户就离开了该页面,这时就需要能够取消剩余正在进行的请求。此外,如果页面会被缓存,并且用户返回该页面时希望避免重复发起所有请求,则可以实现一种“继续任务”的机制。这一机制实际上较为简单,只需要过滤掉那些已经被正确赋值的数据项即可,从而只对那些还未完成的数据发起请求。

这种设计不仅能提高用户体验,还能有效地减少服务器负载和网络流量消耗。

通过Promise实现分批发起并处理接口请求

Promise

这里的 httpRequest 方法需要根据您的具体项目环境进行调整。例如,在我的uni-app项目中,HTTP请求使用的是 uni.request。如果您使用的是其他框架如axios或ajax,那么您需要相应地修改 BatchHttp 中的部分代码以适应这些框架的特点。特别需要注意的是 cancelAll() 函数,如果您的HTTP取消请求的方式与这里不同,那么这部分功能也需要做相应的调整。例如,如果您使用的是 fetch 请求,除了需要修改 cancelAll 功能外,还需要在 singleRequest 方法中采用不同的方式来收集请求任务,因为 fetch 本身不支持取消请求,需要借助 AbortController 来实现这一功能。

总的来说,不论您使用的是哪种请求框架,都可以考虑自行封装一个类似于axios的 request.js 文件,其中返回的对象应该包含一个 abort() 方法来支持取消请求的功能。这样,即使您的项目采用了不同的请求库,上述的 BatchHttp 实现也可以被很好地应用。

简单案例测试 -- batch-promise-test.html

  <!DOCTYPE html>
  <html lang="en">
 
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
 
  <body>
 
  </body>
  <script>
 
    /**
     * 批量请求封装
     */
    class BatchHttp {
 
  	/** 
  	 * 构造函数 
  	 * */
  	constructor() {
  	}
 
  	/** 
  	 * 单个数据项请求 
  	 * @private
  	 * @param {Object} reqOptions - 请求配置
  	 * @param {Object} item - 数据项 
  	 * @returns {Promise} 请求Promise
  	*/
  	#singleRequest(item) {
  	  return new Promise((resolve, _reject) => {
  		// 模拟异步请求
  		console.log(`发起模拟异步请求 padding...: 【${item}】`)
  		setTimeout(() => {
  		  console.log(`模拟异步请求 success -- 【 ${item}】`)
  		  resolve()
  		}, 200 + Math.random() * 800)
  	  })
  	}
 
  	#chunk(array, size) {
  	  const chunks = []
  	  let index = 0
 
  	  while (index < array.length) {
  		chunks.push(array.slice(index, size + index))
  		index += size
  	  }
 
  	  return chunks
  	}
 
  	/**
  	 * 批量请求控制
  	 * @private
  	 * @async
  	 * @returns {Promise}
  	*/
  	async #batchRequest() {
  	  const promiseArray = []
  	  let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
 
  	  data.forEach((item, index) => {
  		// 原来的错误逻辑(原来的逻辑,导致所有的 Promise 回调函数都会被直接执行,那么就只有对 response 进行分批的功能了)
  		// const requestPromise = this.#singleRequest(item)
  		// promiseArray.push(requestPromise)
 
  		// -- 修改为:
  		promiseArray.push(index)
  	  })
 
  	  const promiseChunks = this.#chunk(promiseArray, 10) // 切分成 n 个请求为一组
 
  	  let groupIndex = 1
  	  for (let ckg of promiseChunks) {
  		// -- 修改后新增逻辑(在发起一组请求时,收集该组对应的 Promiise 成员)
  		const ck = ckg.map(idx => this.#singleRequest(data[idx]))
  		// 发起一组请求
  		const ckRess = await Promise.all(ck) // 控制并发数
  		console.log(`------ 第${groupIndex}组分批发起完毕 --------`)
  		groupIndex += 1
  	  }
  	}
 
  	/**
  	 * 执行批量请求操作
  	 */
  	exec(options) {
  	  this.#batchRequest(options)
  	}
    }
 
    const batchHttp = new BatchHttp()
    setTimeout(() => {
  	batchHttp.exec()
    }, 2000)
  </script>
 
  </html>

 

BatchHttp.js

  // 注:这里的 httpRequest 请根据自己项目而定,比如我的项目是uniapp,里面的http请求是 uni.request,若你的项目是 axios 或者 ajax,那就根据它们来对 BatchHttp 中的某些部分
  import httpRequest from './httpRequest.js'
 
  /**
   * 批量请求封装
   */
  export class BatchHttp {
 
  	/** 
  	 * 构造函数 
  	 * @param {Object} http - http请求对象(该http请求拦截器里切勿带有任何有关ui的功能,比如加载对话框、弹窗提示框之类),用于发起请求,该http请求对象必须满足:返回一个包含取消请求函数的对象,因为在 this.cancelAll() 函数中会使用到
  	 * @param {string} [passFlagProp=null] - 用于识别是否忽略某些数据项的字段名(借此可实现“继续上一次完成的批量请求”);如:passFlagProp='url' 时,在执行 exec 时,会过滤掉 items['url'] 不为空的数据,借此可以实现“继续上一次完成的批量请求”,避免每次都重复所有请求
  	 */ 
  	constructor(http=httpRequest, passFlagProp=null) {
  		/** @private @type {Object[]} 请求任务数组 */
  		this.resTasks = []
  		/** @private @type {Object} uni.request对象 */
  		this.http = http
  		/** @private @type {boolean} 取消请求标志 */
  		this.canceled = false
  		/** @private @type {string|null} 识别跳过数据的属性 */
  		this.passFlagProp = passFlagProp
  	}
 
 
  	/**
  	 * 将数组拆分成多个 size 长度的小数组
  	 * 常用于批量处理控制并发等场景
  	 * @param {Array} array - 需要拆分的数组
  	 * @param {number} size - 每个小数组的长度
  	 * @returns {Array} - 拆分后的小数组组成的二维数组
  	*/
  	#chunk(array, size) {
  		const chunks = []
  		let index = 0
 
  		while(index < array.length) {
  		chunks.push(array.slice(index, size + index))
  		index += size;
  		}
 
  		return chunks
  	}
 
  	/** 
  	 * 单个数据项请求 
  	 * @private
  	 * @param {Object} reqOptions - 请求配置
  	 * @param {Object} item - 数据项 
  	 * @returns {Promise} 请求Promise
  	*/
  	#singleRequest(reqOptions, item) {
  		return new Promise((resolve, _reject) => {
  			const task = this.http({
  				url: reqOptions.url, 
  				method: reqOptions.method || 'GET',
  				data: reqOptions.data,
  				success: res => {
  					resolve({sourceItem:item, res})
  				}
  			})
  			this.resTasks.push(task)
  		})
  	}
 
  	/**
  	 * 批量请求控制
  	 * @private
  	 * @async
  	 * @param {Object} options - 函数参数项
  	 * @param {Array} options.items - 数据项数组
  	 * @param {Object} options.reqOptions - 请求配置  
  	 * @param {number} [options.concurrentNum=10] - 并发数
  	 * @param {Function} [options.chunkCallback] - 分块回调 
  	 * @returns {Promise}
  	*/
  	async #batchRequest({items, reqOptions, concurrentNum = 10, chunkCallback=(ress)=>{}}) {
  		const promiseArray = []
  		let data = []
  		const passFlagProp = this.passFlagProp
  		if(!passFlagProp) {
  			data = items
  		} else {
  			// 若设置独立 passFlagProp 值,则筛选出对应属性值为空的数据(避免每次都重复请求所有数据,实现“继续未完成的批量请求任务”)
  			data = items.filter(d => !Object.hasOwnProperty.call(d, passFlagProp) || !d[passFlagProp])
  		}
  		// --
  		if(data.length === 0) return
 
  		data.forEach((item,index) => {
  			// 原来的错误逻辑(原来的逻辑,导致所有的 Promise 回调函数都会被直接执行,那么就只有对 response 进行分批的功能了)
  			// const requestPromise = this.#singleRequest(reqOptions, item)
  			// promiseArray.push(requestPromise)
  			// -- 修改为:这里暂时只记录下想对应的 data 的数组索引,以便分组用,当然这部分有关分组代码还可以进行精简,比如直接使用 data.map进行收集等方式,但是为了与之前错误逻辑形成对比,这篇文章里还是这样写比较完整
  			promiseArray.push(index)
  		})
 
  		const promiseChunks = this.#chunk(promiseArray, concurrentNum) // 切分成 n 个请求为一组
 
  		for (let ckg of promiseChunks) {
  			// -- 修改后新增逻辑(在发起一组请求时,收集该组对应的 Promiise 成员)
  			const ck = ckg.map(idx => this.#singleRequest(data[idx]))
  			// 若当前处于取消请求状态,则直接跳出
  			if(this.canceled) break
  			// 发起一组请求
  			const ckRess = await Promise.all(ck) // 控制并发数
  			chunkCallback(ckRess) // 每完成组请求,都进行回调
  		}
  	}
 
  	/**
  	 * 设置用于识别忽略数据项的字段名
  	 * (借此参数可实现“继续上一次完成的批量请求”);
  	 * 如:passFlagProp='url' 时,在执行 exec 时,会过滤掉 items['url'] 不为空的数据,借此可以实现“继续上一次完成的批量请求”,避免每次都重复所有请求
  	 * @param {string} val 
  	 */
  	setPassFlagProp(val) {
  		this.passFlagProp = val
  	}
 
  	/**
  	 * 执行批量请求操作
  	 * @param {Object} options - 函数参数项
  	 * @param {Array} options.items - 数据项数组
  	 * @param {Object} options.reqOptions - 请求配置  
  	 * @param {number} [options.concurrentNum=10] - 并发数
  	 * @param {Function} [options.chunkCallback] - 分块回调 
  	 */
  	exec(options) {
  		this.canceled = false
  		this.#batchRequest(options)
  	}
 
  	/**
  	 * 取消所有请求任务
  	 */
  	cancelAll() {
  		this.canceled = true
  		for(const task of this.resTasks) {
  			task.abort()
  		}
  		this.resTasks = []
  	}
  }

 

通过Promise实现分批发起处理接口请求的调用示例

考虑到示例项目是基于uni-app的,为了便于说明,我将直接提供一段在uni-app页面Vue组件中的使用案例。请注意,这里展示的代码仅包含关键部分,因此可能看起来较为简略,但它足以帮助您理解实现方法。请参考以下代码示例:

  <template>
  	<view v-for="item of list" :key="item.key">
  		<image :src="item.url"></image>
  	</view>
  	</template>
  	<script>
  	import { BatchHttp } from '@/utils/BatchHttp.js'
 
  	export default {
  		data() {
  			return {
  				isLoaded: false,
  				batchHttpInstance: null,
  				list:[]
  			}
  		},
  		onLoad(options) {
  			this.queryList()
  		},
  		onShow() {
  			// 第一次进页面时,onLoad 和 onShow 都会执行,onLoad 中 getList 已调用 batchQueryUrl,这里仅对缓存页面后再次进入该页面有效
  			if(this.isLoaded) {
  				// 为了实现继续请求上一次可能未完成的批量请求,再次进入该页面时,会检查是否存在未完成的任务,若存在则继续发起批量请求
  				this.batchQueryUrl(this.dataList)
  			}
  			this.isLoaded = true
  		},
  		onHide() {
  			// 页面隐藏时,会直接取消所有批量请求任务,避免占用���源(下次进入该页面会检查未完成的批量请求任务并执行继续功能)
  			this.cancelBatchQueryUrl()
  		},
  		onUnload() {
  			// 页面销毁时,直接取消批量请求任务
  			this.cancelBatchQueryUrl()
  		},
  		onBackPress() {
  			// 路由返回时,直接取消批量请求任务(虽然路由返回也会执行onHide事件,但是无所胃都写上,会判断当前有没有任务的)
  			this.cancelBatchQueryUrl()
  		},
  		methods: {
  			async queryList() {
  				// 接口不方法直接贴的,这里是模拟的列表接口
  				const res = await mockHttpRequest()
  				this.list = res.data
 
  				// 发起批量请求
  				// 用 nextTick 也行,只要确保批量任务在列表dom已挂载完成之后执行即可
  				setTimeout(()=>{this.batchQueryUrl(resData)},0)
  			},
  			/**
  			 * 批量处理图片url的接口请求
  			 * @param {*} data 
  			 */
  			 batchQueryUrl(items) {
  				let batchHttpInstance = this.batchHttpInstance
  				// 判定当前是否有正在执行的批量请求任务,有则直接全部取消即可
  				if(!!batchHttpInstance) {
  					batchHttpInstance.cancelAll()
  					this.batchHttpInstance = null
  					batchHttpInstance = null
  				}
  				// 实例化对象
  				batchHttpInstance = new BatchHttp()
  				// 设置过滤数据的属性名(用于实现继续任务功能)
  				batchHttpInstance.setPassFlagProp('url') // 实现回到该缓存页面是能够继续批量任务的关键一步 <-----
  				const reqOptions = { url: '/api/product/url' }
  				batchHttpInstance.exec({items, reqOptions, chunkCallback:(ress)=>{
  					let newDataList = this.dataList
  					for(const r of ress) {
  						newDataList = newDataList.map(d => d.feId === r['sourceItem'].feId ? {...d,url:r['res'].msg} : d)
  					}
 
  					this.dataList = newDataList
  				}})
 
  				this.batchHttpInstance = batchHttpInstance
  			},
  			/**
  			 * 取消批量请求
  			 */
  			cancelBatchQueryUrl() {
  				if(!!this.batchHttpInstance) {
  					this.batchHttpInstance.cancelAll()
  					this.batchHttpInstance = null
  				}
  			},
  		}
  	}
  	</script>