Files
Yiling-J b35c824a27 feat(transcode): optimize video operations using ffmpeg http range requests (#393)
* feat(transcode): optimize video operations using ffmpeg http range requests

* fix(transcode): preserve non-retryable errors and ensure mapConcurrent settles on rejection
2026-09-08 10:17:15 +08:00

43 lines
1011 B
TypeScript

/**
* Maps an array of items with an async mapping function subject to a concurrency limit.
* Results are returned in the same order as the input items array.
*/
export async function mapConcurrent<T, TResult>(
items: T[],
limit: number,
fn: (item: T, index: number) => Promise<TResult>,
): Promise<TResult[]> {
if (items.length === 0) {
return []
}
const concurrency = Math.max(1, Math.min(limit, items.length))
const results: TResult[] = new Array(items.length)
let nextIndex = 0
let firstError: unknown = null
let hasError = false
const workers = Array.from({ length: concurrency }, async () => {
while (!hasError && nextIndex < items.length) {
const idx = nextIndex++
try {
results[idx] = await fn(items[idx], idx)
} catch (err) {
if (!hasError) {
hasError = true
firstError = err
}
break
}
}
})
await Promise.all(workers)
if (hasError) {
throw firstError
}
return results
}