Created
August 14, 2020 08:01
-
-
Save lionelB/aad81256d8250da590a56bde4895aa1f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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; | |
} |
This file contains hidden or 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
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