Created
May 30, 2018 23:38
-
-
Save mbektimirov/91c5a7174e2c3729b7835f6b1d20e25d 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
function getRandomInt(min, max) { | |
return Math.floor(Math.random() * (max - min)) + min; | |
} | |
function createFakeQueries(count, minTime, maxTime) { | |
return Array(count) | |
.fill() | |
.map((_, i) => { | |
const time = getRandomInt(minTime, maxTime); | |
const queryCaller = () => | |
new Promise(resolve => { | |
console.log('Starting query: %s, %d ms', i, time); | |
setTimeout(() => { | |
console.log('Finished query: %s, %d ms', i, time); | |
resolve({ queryNumber: i, time }); | |
}, time); | |
}); | |
return queryCaller; | |
}); | |
} | |
const queue = createFakeQueries(10, 3000, 5000); | |
const result = []; | |
const limit = 3; | |
let activeQueries = 0; | |
function shift(resolve) { | |
if (queue.length > 0) { | |
if (activeQueries < 3) { | |
const remain = limit - activeQueries; | |
const shifted = queue.splice(0, remain); | |
console.log('taking:', remain); | |
processQueue(shifted, resolve); | |
} | |
} else { | |
Promise.all(result).then(resolve); | |
} | |
} | |
function processQueue(shifted = [], resolve) { | |
shifted.forEach(queryCaller => { | |
activeQueries++; | |
const query = queryCaller(); | |
query.then(() => { | |
activeQueries--; | |
shift(resolve); | |
}); | |
result.push(query); | |
}); | |
} | |
function parallel(argument) { | |
return new Promise((resolve, reject) => { | |
shift(resolve, reject); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment