简单案例测试 -- 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>