将 responsiveGetPages 更改为并行的

This commit is contained in:
Rinne 2025-04-28 11:48:57 +08:00
parent 46710c8f42
commit 777e2d3d9b

View File

@ -194,27 +194,41 @@ export const responsiveGetPages = <T = any>(config: {
responsivePromise = new Promise(resolveResponsive => {
;(async () => {
const { api, getList, getTotal } = config
let page = 1
let total = Infinity
const result = []
while (result.length < total) {
const json = await api(page)
const result: T[] = []
const tasks: Promise<T[]>[] = []
const fetchPage = async (p: number): Promise<T[]> => {
const json = await api(p)
if (json.code !== 0) {
console.warn(
`api failed in ajax.getPages. message = ${json.message}, page = ${page}, total = ${total}, api = `,
`api failed in ajax.getPages. message = ${json.message}, page = ${p}, total = ${total}, api = `,
api,
)
return []
}
const list = getList(json)
result.push(...list)
if (page === 1) {
resolveResponsive(result)
}
page++
if (total === Infinity) {
total = getTotal(json)
}
return getList(json)
}
// 请求第一次获得total
const firstReq = await api(1)
result.push(...getList(firstReq))
total = getTotal(firstReq)
const pageSize = getList(firstReq).length || 1 // 防止为0
const totalPages = Math.ceil(total / pageSize)
resolveResponsive(result) // 第一页
if (totalPages === 1) {
resolveTotal(result)
return
}
console.log(totalPages)
// 收集Promise
for (let i = 2; i <= totalPages; i++) {
tasks.push(fetchPage(i))
}
// 等所有并发完成
const lists = await Promise.all(tasks)
result.push(...lists.flat())
resolveTotal(result)
})()
})
@ -237,6 +251,7 @@ export const getPages = async <T = any>(config: {
const result = await total
return result
}
/** bilibili API 标准响应 */
export interface BilibiliApiResponse {
code: number
@ -246,6 +261,7 @@ export interface BilibiliApiResponse {
data: any
result?: any
}
/**
* bilibili API
* @param apiPromise API Promise