-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprottle.js
57 lines (48 loc) · 1.15 KB
/
prottle.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const EventEmitter = require('events');
module.exports = (limit, arr) => {
limit = parseInt(limit);
if (isNaN(limit) || limit <= 0) {
return Promise.reject(Error('Limit must be at least 1'));
}
if (!Array.isArray(arr)) {
return Promise.reject(Error('Array of promises required'));
}
const promises = [].concat(arr);
const results = [];
const emitter = new EventEmitter();
const run = (batch, id) => {
Promise.all(batch.map(
(fn) => Promise.resolve(fn())
))
.then((res) => {
results.push.apply(results, res);
emitter.emit(`end:${id}`);
})
.catch((err) => {
emitter.emit('error', err);
});
};
let add = (batch, id) => {
if (id === 0) {
return run(batch, id);
}
emitter.once(`end:${id-1}`, () => run(batch, id));
};
let idx = -1;
while (promises.length) {
add(
promises.splice(0, limit),
++idx
);
}
return new Promise((resolve, reject) => {
emitter
.once(`end:${idx}`, () => {
resolve(results);
})
.once('error', err => {
emitter.removeAllListeners();
reject(err);
});
});
};