problems(js): add “2636. Promise Pool”
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
dbf39a2ad0
commit
4bb6d712e2
1 changed files with 38 additions and 0 deletions
38
problems/promise-pool.js
Normal file
38
problems/promise-pool.js
Normal file
|
@ -0,0 +1,38 @@
|
||||||
|
/**
|
||||||
|
* @param {Function[]} functions
|
||||||
|
* @param {number} n
|
||||||
|
* @return {Function}
|
||||||
|
*/
|
||||||
|
var promisePool = async function(functions, n) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let in_progress = 0;
|
||||||
|
let next = 0;
|
||||||
|
|
||||||
|
function progress() {
|
||||||
|
if (next >= functions.length) {
|
||||||
|
if (in_progress == 0) {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (in_progress < n && next < functions.length) {
|
||||||
|
in_progress++;
|
||||||
|
|
||||||
|
functions[next++]().then(() => {
|
||||||
|
in_progress--;
|
||||||
|
progress();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
progress();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* const sleep = (t) => new Promise(res => setTimeout(res, t));
|
||||||
|
* promisePool([() => sleep(500), () => sleep(400)], 1)
|
||||||
|
* .then(console.log) // After 900ms
|
||||||
|
*/
|
Loading…
Reference in a new issue