From 777e2d3d9b7a5ba06a329f682247a143a79c7c5f Mon Sep 17 00:00:00 2001 From: Rinne Date: Mon, 28 Apr 2025 11:48:57 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=86=20responsiveGetPages=20=E6=9B=B4?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E5=B9=B6=E8=A1=8C=E7=9A=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/ajax.ts | 44 ++++++++++++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/src/core/ajax.ts b/src/core/ajax.ts index f343cd196..8b5a1e27c 100644 --- a/src/core/ajax.ts +++ b/src/core/ajax.ts @@ -194,27 +194,41 @@ export const responsiveGetPages = (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[] = [] + + const fetchPage = async (p: number): Promise => { + 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 (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