-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path2636-promise-pool.js
More file actions
34 lines (32 loc) · 850 Bytes
/
2636-promise-pool.js
File metadata and controls
34 lines (32 loc) · 850 Bytes
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
/**
* @param {Function[]} functions
* @param {number} n
* @return {Promise<any>}
*/
var promisePool = async function (functions, n) {
return new Promise((resolve, reject) => {
let inProgressCount = 0;
let functionIndex = 0;
function helper() {
if (functionIndex >= functions.length) {
if (inProgressCount === 0) resolve();
return;
}
while (inProgressCount < n && functionIndex < functions.length) {
inProgressCount++;
const promise = functions[functionIndex]();
functionIndex++;
promise.then(() => {
inProgressCount--;
helper();
});
}
}
helper();
});
};
/**
* const sleep = (t) => new Promise(res => setTimeout(res, t));
* promisePool([() => sleep(500), () => sleep(400)], 1)
* .then(console.log) // After 900ms
*/