Created
April 14, 2022 17:08
-
-
Save aheld/814441cf27b3fef1eea809dfdae57e95 to your computer and use it in GitHub Desktop.
simple demo to batch promises as opposed to promise.all
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
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