24 lines
808 B
TypeScript
24 lines
808 B
TypeScript
// Keep a few transfers in flight without flooding mobile connections or allocating
|
|
// a promise/network request for every selected file at once.
|
|
export const UPLOAD_CONCURRENCY = 3;
|
|
|
|
export async function runUploadQueue<T>(
|
|
items: readonly T[],
|
|
upload: (item: T, index: number) => Promise<void>,
|
|
) {
|
|
let next = 0;
|
|
const errors: unknown[] = [];
|
|
await Promise.all(Array.from({ length: Math.min(UPLOAD_CONCURRENCY, items.length) }, async () => {
|
|
while (next < items.length) {
|
|
const index = next++;
|
|
try {
|
|
await upload(items[index]!, index);
|
|
} catch (error) {
|
|
errors.push(error);
|
|
}
|
|
}
|
|
}));
|
|
// Never release the batch's busy guard while other transfers are still running.
|
|
if (errors.length) throw new AggregateError(errors, "Some uploads failed");
|
|
}
|