Skip to content

Instantly share code, notes, and snippets.

@javilobo8
Created May 17, 2024 12:43
Show Gist options
  • Save javilobo8/f25398df69d101011779e6739ce9e543 to your computer and use it in GitHub Desktop.
Save javilobo8/f25398df69d101011779e6739ce9e543 to your computer and use it in GitHub Desktop.
batch-operation.ts
export async function batchOperation<T>(items: T[], operation: (items: T[], index: number) => Promise<void>, batchSize = 1000) {
let continueOperation = true;
let cursor = 0;
let successOperations = 0;
let erroredOperations = 0;
while (continueOperation) {
const batch = items.slice(cursor, cursor + batchSize);
if (batch.length) {
try {
await operation(batch, cursor);
successOperations += batch.length;
} catch (error) {
console.error('Error executing batch operation', error);
erroredOperations += batch.length;
}
cursor += batchSize;
} else {
continueOperation = false;
}
}
return {
successOperations,
erroredOperations,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment