( fn: (mergedParams: T[]) => Promise<R[]>, windowMs = 200 )
| 14 | * @param windowMs 窗口期 |
| 15 | */ |
| 16 | export function createAutoMergedRequest<T, R>( |
| 17 | fn: (mergedParams: T[]) => Promise<R[]>, |
| 18 | windowMs = 200 |
| 19 | ): (params: T) => Promise<R> { |
| 20 | let queue: QueueItem<T, R>[] = []; |
| 21 | let timer: number | null = null; |
| 22 | |
| 23 | async function submitQueue() { |
| 24 | timer = null; // 清空计时器以接受后续请求 |
| 25 | const _queue = [...queue]; |
| 26 | queue = []; // 清空队列 |
| 27 | |
| 28 | try { |
| 29 | const list = await fn(_queue.map((q) => q.params)); |
| 30 | _queue.forEach((q1, i) => { |
| 31 | q1.resolve(list[i]); |
| 32 | }); |
| 33 | } catch (err) { |
| 34 | _queue.forEach((q2) => { |
| 35 | q2.reject(err); |
| 36 | }); |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | return (params: T): Promise<R> => { |
| 41 | if (!timer) { |
| 42 | // 如果没有开始窗口期,则创建 |
| 43 | timer = window.setTimeout(() => { |
| 44 | submitQueue(); |
| 45 | }, windowMs); |
| 46 | } |
| 47 | |
| 48 | return new Promise<R>((resolve, reject) => { |
| 49 | queue.push({ |
| 50 | params, |
| 51 | resolve, |
| 52 | reject, |
| 53 | }); |
| 54 | }); |
| 55 | }; |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * 创建一个自动拆分请求参数的函数 |
no test coverage detected