forked from json-logic/json-logic-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncPool.js
More file actions
45 lines (42 loc) · 814 Bytes
/
asyncPool.js
File metadata and controls
45 lines (42 loc) · 814 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
35
36
37
38
39
40
41
42
43
44
45
// @ts-check
'use strict'
function timeout (n) {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, n)
})
}
function asyncPool ({
free = [],
max = 10,
created = free.length,
create = () => {}
} = {}) {
const pool = async function () {
if (free.length) {
const func = free.pop()
const promise = func(...arguments)
// return the stateful function
promise
.then(() => {
free.push(func)
})
.catch(() => {
free.push(func)
})
return promise
} else {
if (created < max) {
created++
free.push(await create())
}
while (!free.length) {
await timeout(250)
}
return pool(...arguments)
}
}
return pool
}
export default asyncPool