Created
December 4, 2021 16:54
-
-
Save azarmadr/62ec616ff7863f6409da743b8c061bf8 to your computer and use it in GitHub Desktop.
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
const chunk = (arr, n) => { | |
if(n<=0)throw new Error('First argument to splitEvery must be a positive integer') | |
var result = [],idx = 0; | |
while(idx<arr.length)result.push(arr.slice(idx,idx+=n)) | |
return result | |
} | |
const fetchProxy=()=> new Promise((resolve, reject) => { | |
const randomWait = 300*Math.random(); | |
setTimeout(() => resolve(randomWait), randomWait); | |
}); | |
const reqCount = 50; | |
const arrayToWork = […Array(reqCount).keys()]; | |
console.log(startTime=Date.now()) | |
Promise.all(arrayToWork.map(fetchProxy)).then(() => console.log({'Parallel ~ 300ms':Date.now()-startTime})); | |
Promise.resolve( | |
arrayToWork.reduce((memo,i)=>memo.then(fetchProxy),Promise.resolve()) | |
).then(()=>console.log({[`Sequential ~ ${reqCount}*300ms`]:Date.now()-startTime})) | |
const chunkSize = 25; // number that reflects your bandwidth's capacity | |
Promise.resolve(chunk(arrayToWork,chunkSize).reduce((memo,pieceOfChunk)=> | |
memo.then(()=>Promise.all(pieceOfChunk.map(fetchProxy))),Promise.resolve() | |
)).then(()=>console.log({[`Parallel and Sequential ~ < ${reqCount}/${chunkSize} * 300ms`]:Date.now()-startTime})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment