Last active
January 31, 2020 09:55
-
-
Save sgmonda/ae40efcdea944b67ce36e66bd1cca526 to your computer and use it in GitHub Desktop.
Promise runner example for sgmonda.com
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
// 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