/** 按输入顺序执行有界并发映射,避免一次创建过多异步任务。 */ export async function mapWithConcurrency( items: readonly T[], concurrency: number, worker: (item: T, index: number) => Promise, ): Promise { if (items.length === 0) { return []; } const workerCount = Math.max(1, Math.min(items.length, Math.floor(concurrency) || 1)); const results = Array.from({ length: items.length }); let nextIndex = 0; let failed = false; /** 领取并处理下一个尚未执行的输入项。 */ async function runWorker(): Promise { for (;;) { if (failed) { return; } const index = nextIndex; nextIndex += 1; if (index >= items.length) { return; } try { results[index] = await worker(items[index] as T, index); } catch (error) { failed = true; throw error; } } } await Promise.all(Array.from({ length: workerCount }, () => runWorker())); return results; }