Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Promise runner example for sgmonda.com
// Usage: $ node promiseRunnerExample.js <mode>
// Where <mode> can be one of the following: 'serie', 'parallel', 'parallelLimit'
const numbers = Array(50).fill(1).map((_, index) => index);
const getNumber = (num) => new Promise((resolve) => {
const delay = Math.random() * 1000;
const fun = () => resolve(num);
setTimeout(() => {
process.stdout.write(`${num}, `);
fun();
}, delay);
});
async function runInSerie() {
for (const num of numbers) await getNumber(num);
console.log("Finished");
}
async function runInParallel() {
const promises = numbers.map(getNumber);
await Promise.all(promises);
console.log("Finished");
}
async function promiseRunner(funs, concurrency) {
let result = [];
while (funs.length > 0) {
const group = funs.splice(0, concurrency);
const promises = group.map(f => f());
const partial = await Promise.all(promises);
result = result.concat(partial);
}
return result;
}
async function runInParallelLimit(concurrency) {
const promiseCreators = numbers.map(num => () => getNumber(num));
await promiseRunner(promiseCreators, 5);
console.log("Finished");
}
(async () => {
const mode = process.argv[2];
if (mode === 'serie') await runInSerie();
else if (mode === 'parallel') await runInParallel();
else if (mode === 'parallelLimit') await runInParallelLimit(5);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment