Skip to content

Instantly share code, notes, and snippets.

@lionelB
Created August 14, 2020 08:01
Show Gist options
  • Save lionelB/aad81256d8250da590a56bde4895aa1f to your computer and use it in GitHub Desktop.
Save lionelB/aad81256d8250da590a56bde4895aa1f to your computer and use it in GitHub Desktop.
async function batchPromise(items, handler, batchSize) {
const array = items.slice();
let results = [];
let i = 0;
while (array.length) {
const res = await Promise.all(array.splice(0, batchSize).map(handler));
console.log(`Performed operation for batch ${++i}.`);
results = results.concat(res);
}
return results;
}
async function test() {
async function testHandler(param) {
return new Promise((resolve) => {
setTimeout(() => {
console.log(`Performed operation for resource ${param}.`);
resolve(`-->${param}`);
}, 300);
});
}
const array = Array.from({ length: 10 }, (_, i) => i + 1);
const handler = (id) => testHandler(id);
const results = await batchPromise(array, handler, 3);
console.log(results);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment