经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Omi » 查看文章
js需要同时发起百条接口请求怎么办?--通过Promise实现分批处理接口请求
来源:cnblogs  作者:二价亚铁  时间:2024/7/17 10:58:41  对本文有异议

如何通过 Promise 实现百条接口请求?
实际项目中遇到需要发起上百条Promise接口请求怎么办?

前言

  • 不知你项目中有没有遇到过这样的情况,反正我的实际工作项目中真的遇到了这种玩意,一个接口获取一份列表,列表中的每一项都有一个属性需要通过另一个请求来逐一赋值,然后就有了这份封装
  • 真的是很多功能都是被逼出来的
  • 这份功能中要提醒一下:批量请求最关键的除了分批功能之外,适当得取消任务和继续任务也很重要,比如用户到了这个页面后,正在发起百条数据请求,但是这些批量请求还没完全执行完,用户离开了这个页面,此时就需要取消剩下正在发起的请求了,而且如果你像我的遇到的项目一样,页面还会被缓存,那么为了避免用户回到这个页面,所有请求又重新发起一遍的话,就需要实现继续任务的功能,其实这个继续任务比断点续传简单多了,就是过滤到那些已经赋值的数据项就行了
  • 如果看我啰啰嗦嗦一堆烂东西没看明白的话,就直接看下面的源码吧

源码在此!

  • 【注】:这里的 httpRequest 请根据自己项目而定,比如我的项目是uniapp,里面的http请求是 uni.request,若你的项目是 axios 或者 ajax,那就根据它们来对 BatchHttp 中的某些部分进行相应的修改

  • 比如:其中的 cancelAll() 函数,若你的 http 取消请求的方式不同,那么这里取消请求的功能就需要相应的修改,若你使用的是 fetch 请求,那除了修改 cancelAll 功能之外,singleRequest 中收集请求任务的方式也要修改,因为 fetch 是不可取消的,需要借助 AbortController 来实现取消请求的功能,

  • 提示一下,不管你用的是什么请求框架,你都可以自己二次封装一个 request.js,功能就仿照 axios 这种,返回的对象中包含一个 abort() 函数即可,那么这份 BatchHttp 也就能适用啦

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

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

    1. // 注:这里的 httpRequest 请根据自己项目而定,比如我的项目是uniapp,里面的http请求是 uni.request,若你的项目是 axios 或者 ajax,那就根据它们来对 BatchHttp 中的某些部分
    2. import httpRequest from './httpRequest.js'
    3. /**
    4. * 批量请求封装
    5. */
    6. export class BatchHttp {
    7. /**
    8. * 构造函数
    9. * @param {Object} http - http请求对象(该http请求拦截器里切勿带有任何有关ui的功能,比如加载对话框、弹窗提示框之类),用于发起请求,该http请求对象必须满足:返回一个包含取消请求函数的对象,因为在 this.cancelAll() 函数中会使用到
    10. * @param {string} [passFlagProp=null] - 用于识别是否忽略某些数据项的字段名(借此可实现“继续上一次完成的批量请求”);如:passFlagProp='url' 时,在执行 exec 时,会过滤掉 items['url'] 不为空的数据,借此可以实现“继续上一次完成的批量请求”,避免每次都重复所有请求
    11. */
    12. constructor(http=httpRequest, passFlagProp=null) {
    13. /** @private @type {Object[]} 请求任务数组 */
    14. this.resTasks = []
    15. /** @private @type {Object} uni.request对象 */
    16. this.http = http
    17. /** @private @type {boolean} 取消请求标志 */
    18. this.canceled = false
    19. /** @private @type {string|null} 识别跳过数据的属性 */
    20. this.passFlagProp = passFlagProp
    21. }
    22. /**
    23. * 将数组拆分成多个 size 长度的小数组
    24. * 常用于批量处理控制并发等场景
    25. * @param {Array} array - 需要拆分的数组
    26. * @param {number} size - 每个小数组的长度
    27. * @returns {Array} - 拆分后的小数组组成的二维数组
    28. */
    29. #chunk(array, size) {
    30. const chunks = []
    31. let index = 0
    32. while(index < array.length) {
    33. chunks.push(array.slice(index, size + index))
    34. index += size;
    35. }
    36. return chunks
    37. }
    38. /**
    39. * 单个数据项请求
    40. * @private
    41. * @param {Object} reqOptions - 请求配置
    42. * @param {Object} item - 数据项
    43. * @returns {Promise} 请求Promise
    44. */
    45. #singleRequest(reqOptions, item) {
    46. return new Promise((resolve, _reject) => {
    47. const task = this.http({
    48. url: reqOptions.url,
    49. method: reqOptions.method || 'GET',
    50. data: reqOptions.data,
    51. success: res => {
    52. resolve({sourceItem:item, res})
    53. }
    54. })
    55. this.resTasks.push(task)
    56. })
    57. }
    58. /**
    59. * 批量请求控制
    60. * @private
    61. * @async
    62. * @param {Object} options - 函数参数项
    63. * @param {Array} options.items - 数据项数组
    64. * @param {Object} options.reqOptions - 请求配置
    65. * @param {number} [options.concurrentNum=10] - 并发数
    66. * @param {Function} [options.chunkCallback] - 分块回调
    67. * @returns {Promise}
    68. */
    69. async #batchRequest({items, reqOptions, concurrentNum = 10, chunkCallback=(ress)=>{}}) {
    70. const promiseArray = []
    71. let data = []
    72. const passFlagProp = this.passFlagProp
    73. if(!passFlagProp) {
    74. data = items
    75. } else {
    76. // 若设置独立 passFlagProp 值,则筛选出对应属性值为空的数据(避免每次都重复请求所有数据,实现“继续未完成的批量请求任务”)
    77. data = items.filter(d => !Object.hasOwnProperty.call(d, passFlagProp) || !d[passFlagProp])
    78. }
    79. // --
    80. if(data.length === 0) return
    81. data.forEach((item,index) => {
    82. // 原来的错误逻辑(原来的逻辑,导致所有的 Promise 回调函数都会被直接执行,那么就只有对 response 进行分批的功能了)
    83. // const requestPromise = this.#singleRequest(reqOptions, item)
    84. // promiseArray.push(requestPromise)
    85. // -- 修改为:这里暂时只记录下想对应的 data 的数组索引,以便分组用,当然这部分有关分组代码还可以进行精简,比如直接使用 data.map进行收集等方式,但是为了与之前错误逻辑形成对比,这篇文章里还是这样写比较完整
    86. promiseArray.push(index)
    87. })
    88. const promiseChunks = this.#chunk(promiseArray, concurrentNum) // 切分成 n 个请求为一组
    89. for (let ckg of promiseChunks) {
    90. // -- 修改后新增逻辑(在发起一组请求时,收集该组对应的 Promiise 成员)
    91. const ck = ckg.map(idx => this.#singleRequest(data[idx]))
    92. // 若当前处于取消请求状态,则直接跳出
    93. if(this.canceled) break
    94. // 发起一组请求
    95. const ckRess = await Promise.all(ck) // 控制并发数
    96. chunkCallback(ckRess) // 每完成组请求,都进行回调
    97. }
    98. }
    99. /**
    100. * 设置用于识别忽略数据项的字段名
    101. * (借此参数可实现“继续上一次完成的批量请求”);
    102. * 如:passFlagProp='url' 时,在执行 exec 时,会过滤掉 items['url'] 不为空的数据,借此可以实现“继续上一次完成的批量请求”,避免每次都重复所有请求
    103. * @param {string} val
    104. */
    105. setPassFlagProp(val) {
    106. this.passFlagProp = val
    107. }
    108. /**
    109. * 执行批量请求操作
    110. * @param {Object} options - 函数参数项
    111. * @param {Array} options.items - 数据项数组
    112. * @param {Object} options.reqOptions - 请求配置
    113. * @param {number} [options.concurrentNum=10] - 并发数
    114. * @param {Function} [options.chunkCallback] - 分块回调
    115. */
    116. exec(options) {
    117. this.canceled = false
    118. this.#batchRequest(options)
    119. }
    120. /**
    121. * 取消所有请求任务
    122. */
    123. cancelAll() {
    124. this.canceled = true
    125. for(const task of this.resTasks) {
    126. task.abort()
    127. }
    128. this.resTasks = []
    129. }
    130. }

调用案例在此!

  • 由于我的项目是uni-app这种,方便起见,我就直接贴上在 uni-app 的页面 vue 组件中的使用案例

  • 案例代码仅展示关键部分,所以比较粗糙,看懂参考即可

    1. <template>
    2. <view v-for="item of list" :key="item.key">
    3. <image :src="item.url"></image>
    4. </view>
    5. </template>
    6. <script>
    7. import { BatchHttp } from '@/utils/BatchHttp.js'
    8. export default {
    9. data() {
    10. return {
    11. isLoaded: false,
    12. batchHttpInstance: null,
    13. list:[]
    14. }
    15. },
    16. onLoad(options) {
    17. this.queryList()
    18. },
    19. onShow() {
    20. // 第一次进页面时,onLoad 和 onShow 都会执行,onLoad 中 getList 已调用 batchQueryUrl,这里仅对缓存页面后再次进入该页面有效
    21. if(this.isLoaded) {
    22. // 为了实现继续请求上一次可能未完成的批量请求,再次进入该页面时,会检查是否存在未完成的任务,若存在则继续发起批量请求
    23. this.batchQueryUrl(this.dataList)
    24. }
    25. this.isLoaded = true
    26. },
    27. onHide() {
    28. // 页面隐藏时,会直接取消所有批量请求任务,避免占用???源(下次进入该页面会检查未完成的批量请求任务并执行继续功能)
    29. this.cancelBatchQueryUrl()
    30. },
    31. onUnload() {
    32. // 页面销毁时,直接取消批量请求任务
    33. this.cancelBatchQueryUrl()
    34. },
    35. onBackPress() {
    36. // 路由返回时,直接取消批量请求任务(虽然路由返回也会执行onHide事件,但是无所胃都写上,会判断当前有没有任务的)
    37. this.cancelBatchQueryUrl()
    38. },
    39. methods: {
    40. async queryList() {
    41. // 接口不方法直接贴的,这里是模拟的列表接口
    42. const res = await mockHttpRequest()
    43. this.list = res.data
    44. // 发起批量请求
    45. // 用 nextTick 也行,只要确保批量任务在列表dom已挂载完成之后执行即可
    46. setTimeout(()=>{this.batchQueryUrl(resData)},0)
    47. },
    48. /**
    49. * 批量处理图片url的接口请求
    50. * @param {*} data
    51. */
    52. batchQueryUrl(items) {
    53. let batchHttpInstance = this.batchHttpInstance
    54. // 判定当前是否有正在执行的批量请求任务,有则直接全部取消即可
    55. if(!!batchHttpInstance) {
    56. batchHttpInstance.cancelAll()
    57. this.batchHttpInstance = null
    58. batchHttpInstance = null
    59. }
    60. // 实例化对象
    61. batchHttpInstance = new BatchHttp()
    62. // 设置过滤数据的属性名(用于实现继续任务功能)
    63. batchHttpInstance.setPassFlagProp('url') // 实现回到该缓存页面是能够继续批量任务的关键一步 <-----
    64. const reqOptions = { url: '/api/product/url' }
    65. batchHttpInstance.exec({items, reqOptions, chunkCallback:(ress)=>{
    66. let newDataList = this.dataList
    67. for(const r of ress) {
    68. newDataList = newDataList.map(d => d.feId === r['sourceItem'].feId ? {...d,url:r['res'].msg} : d)
    69. }
    70. this.dataList = newDataList
    71. }})
    72. this.batchHttpInstance = batchHttpInstance
    73. },
    74. /**
    75. * 取消批量请求
    76. */
    77. cancelBatchQueryUrl() {
    78. if(!!this.batchHttpInstance) {
    79. this.batchHttpInstance.cancelAll()
    80. this.batchHttpInstance = null
    81. }
    82. },
    83. }
    84. }
    85. </script>

原文链接:https://www.cnblogs.com/xw-01/p/18306078

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号