-
Notifications
You must be signed in to change notification settings - Fork 0
/
2636-promise-pool.js
38 lines (37 loc) · 1.01 KB
/
2636-promise-pool.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* @param {Function[]} functions
* @param {number} n
* @return {Function}
*/
var promisePool = async function (functions, n) {
return new Promise((resolve) => {
// inProgress :to keep track of promise
// index: index of current functions in array
let inProgress = 0,
index = 0;
function helper() {
// base case
if (index >= functions.length) {
// if all promises are resolved
if (inProgress === 0) {
resolve();
return;
}
}
while (index < functions.length && inProgress < n) {
inProgress++; // increment because function at current index is executing and promise is pending
functions[index++]().then(() => {
// decremented because promise is resolved
inProgress--;
helper();
});
}
}
helper();
});
};
/**
* const sleep = (t) => new Promise(res => setTimeout(res, t));
* promisePool([() => sleep(500), () => sleep(400)], 1)
* .then(console.log) // After 900ms
*/