File size: 963 Bytes
30c32c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
class AsyncLimiter {
    constructor (callback, maxConcurrent) {
        this.callback = callback;
        this.maxConcurrent = maxConcurrent;
        this._current = 0;
        this._queue = [];
    }

    do (...args) {
        return new Promise((resolve, reject) => {
            this._queue.push([resolve, reject, args]);
            this._startNext();
        });
    }

    _startNext () {
        if (this._current >= this.maxConcurrent || this._queue.length === 0) {
            return;
        }
        this._current++;
        const [resolve, reject, args] = this._queue.shift();
        this.callback.apply(null, args)
            .then(result => {
                resolve(result);
                this._current--;
                this._startNext();
            })
            .catch(error => {
                reject(error);
                this._current--;
                this._startNext();
            });
    }
}

module.exports = AsyncLimiter;