31 lines
895 B
JavaScript
31 lines
895 B
JavaScript
/**
|
|
* Map in input order with bounded parallelism. After the first failure, stop
|
|
* scheduling work and drain every in-flight worker before rejecting.
|
|
*/
|
|
export async function mapBounded(items, limit, worker) {
|
|
if (!Number.isSafeInteger(limit) || limit < 1) throw new Error('并发数量必须为正整数');
|
|
const source = Array.from(items);
|
|
const results = new Array(source.length);
|
|
let next = 0;
|
|
let failed = false;
|
|
let firstError;
|
|
|
|
async function run() {
|
|
while (!failed && next < source.length) {
|
|
const index = next++;
|
|
try {
|
|
results[index] = await worker(source[index], index);
|
|
} catch (error) {
|
|
if (!failed) {
|
|
failed = true;
|
|
firstError = error;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
await Promise.all(Array.from({ length: Math.min(limit, source.length) }, () => run()));
|
|
if (failed) throw firstError;
|
|
return results;
|
|
}
|