Skip to content

Commit de82905

Browse files
authored
Create 2636-promise-pool.js
1 parent 9b39c57 commit de82905

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

2636-promise-pool.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @param {Function[]} functions
3+
* @param {number} n
4+
* @return {Function}
5+
*/
6+
const promisePool = async function(functions, n) {
7+
const it = functions[Symbol.iterator]()
8+
9+
const add = async () => {
10+
const { value, done } = it.next()
11+
if(value) {
12+
await value()
13+
await add()
14+
}
15+
}
16+
17+
const arr = []
18+
for(let i = 0; i < n; i++) {
19+
arr.push(add())
20+
}
21+
22+
return Promise.all(arr)
23+
};
24+
25+
/**
26+
* const sleep = (t) => new Promise(res => setTimeout(res, t));
27+
* promisePool([() => sleep(500), () => sleep(400)], 1)
28+
* .then(console.log) // After 900ms
29+
*/

0 commit comments

Comments
 (0)