Skip to content

Instantly share code, notes, and snippets.

@aheld
Created April 14, 2022 17:08
Show Gist options
  • Save aheld/814441cf27b3fef1eea809dfdae57e95 to your computer and use it in GitHub Desktop.
Save aheld/814441cf27b3fef1eea809dfdae57e95 to your computer and use it in GitHub Desktop.
simple demo to batch promises as opposed to promise.all
job = (input, batchNumber) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Running batch ',batchNumber, 'processing ', input)
resolve('completed ' + input)
}, 1000)
})
}
async function batcher(inputArray, fn, batchSize) {
const results = []
batchNumber = 0
for (let i = 0; i < inputArray.length; i += batchSize) {
batchNumber++
batchRun = inputArray.slice(i, i + batchSize)
.map(input => fn(input, batchNumber))
results.push(...await Promise.all(batchRun))
}
return results
}
inputArray = []
for (let i = 1; i < 100; i++) {
inputArray.push(i)
}
batcher(inputArray, job, 7)
.then(console.log)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment