Restructure download function

This commit is contained in:
Alan Grainger
2026-06-06 21:05:28 +12:00
parent cefe2e81ff
commit b0e0fe0f95
3 changed files with 243 additions and 179 deletions
+21
View File
@@ -0,0 +1,21 @@
/**
* Returns a function that runs at most `limit` async tasks concurrently.
* Tasks queue when the limit is reached and resume in FIFO order.
*/
export function createLimiter (limit: number) {
let active = 0
const queue: Array<() => void> = []
return async function run<T> (fn: () => Promise<T>): Promise<T> {
if (active >= limit) {
await new Promise<void>(resolve => queue.push(resolve))
}
active++
try {
return await fn()
} finally {
active--
const next = queue.shift()
if (next) next()
}
}
}