Skip to content

Instantly share code, notes, and snippets.

@sgmonda
Last active January 31, 2020 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgmonda/ae40efcdea944b67ce36e66bd1cca526 to your computer and use it in GitHub Desktop.
Save sgmonda/ae40efcdea944b67ce36e66bd1cca526 to your computer and use it in GitHub Desktop.
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