JavaScript 使用 Promise 实现接口请求分批处理与取消机制

作者:函数茶馆时间:2026-10-31 12:08:54浏览:462

本文介绍如何使用 JavaScript 的 Promise 封装 BatchHttp 类,实现接口请求的分批处理。核心功能包括控制并发数量、支持批量取消请求以及处理页面缓存后的继续任务。文章提供了基于 uni-app 和原生 JS 的完整代码示例,并说明了如何适配不同 HTTP 库如 axios 或 fetch。

前言

在实际开发中,常遇到这样的场景:调用一个接口获取列表数据,而列表中的每一项都需要通过另一个单独的请求来补充特定属性。为了解决这种嵌套请求导致的性能问题,我封装了以下工具。

很多实用功能都是在具体业务痛点中催生的。

该封装方案有两个关键点:一是分批执行,二是支持任务的取消与恢复。例如,用户进入页面后发起了百条数据的批量请求,若用户在请求全部完成前离开页面,此时应取消剩余未执行的请求。此外,若页面支持缓存,当用户再次返回时,为避免重复发起所有请求,需实现“继续任务”功能。这比断点续传更简单,只需过滤掉已获取数据项即可。若上述说明晦涩,可直接参考后续源码。

代码改进说明

特别感谢网友的热心指正,原代码确实存在逻辑缺陷。

原代码仅对响应结果进行了分批处理,虽然在我老项目的特定场景下侥幸实现了分批发起请求的效果,但逻辑上仍需修正。

感谢 @倔犟小名 和 @月凡丶 的检查。

以下是修正后的代码实现。

源码在此

注意:代码中的 httpRequest 需根据实际项目调整。例如,若使用 uni-app,应替换为 uni.request;若使用 axios 或 ajax,则需相应修改 BatchHttp 中的相关部分。

以 cancelAll() 函数为例,若项目的 HTTP 取消机制不同,需修改此函数。若使用 fetch,由于其原生不可取消,需借助 AbortController 实现。提示:无论使用何种请求框架,建议二次封装一个 request.js,仿照 axios 返回包含 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 = []
    }
}

调用案例在此

鉴于我的项目基于 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>

以上就是 JavaScript 如何使用 Promise 实现分批处理接口请求的详细内容,更多关于 JavaScript Promise 分批处理接口请求的资料请关注本站其它相关文章!

作者最新文章