Created
May 17, 2024 12:43
-
-
Save javilobo8/f25398df69d101011779e6739ce9e543 to your computer and use it in GitHub Desktop.
batch-operation.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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