-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPromise_Pool.js
More file actions
34 lines (33 loc) · 869 Bytes
/
Promise_Pool.js
File metadata and controls
34 lines (33 loc) · 869 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 {Function}
*/
var promisePool = async function(functions, n) {
return new Promise((resolve,reject)=>{
let i=0;
let inprogress=0;
function callback() {
if (i===functions.length && inprogress===0)
{
resolve();
}
while (i<functions.length && inprogress<n)
{
functions[i++]()
.then(()=>
{
inprogress -- ;
callback();
});
inprogress ++;
}
}
callback();
});
};
/**
* const sleep = (t) => new Promise(res => setTimeout(res, t));
* promisePool([() => sleep(500), () => sleep(400)], 1)
* .then(console.log) // After 900ms
*/