Projekt

Obecné

Profil

Stáhnout (1.09 KB) Statistiky
| Větev: | Revize:
1
'use strict';
2
const pTry = require('p-try');
3

    
4
const pLimit = concurrency => {
5
	if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
6
		return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up'));
7
	}
8

    
9
	const queue = [];
10
	let activeCount = 0;
11

    
12
	const next = () => {
13
		activeCount--;
14

    
15
		if (queue.length > 0) {
16
			queue.shift()();
17
		}
18
	};
19

    
20
	const run = (fn, resolve, ...args) => {
21
		activeCount++;
22

    
23
		const result = pTry(fn, ...args);
24

    
25
		resolve(result);
26

    
27
		result.then(next, next);
28
	};
29

    
30
	const enqueue = (fn, resolve, ...args) => {
31
		if (activeCount < concurrency) {
32
			run(fn, resolve, ...args);
33
		} else {
34
			queue.push(run.bind(null, fn, resolve, ...args));
35
		}
36
	};
37

    
38
	const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
39
	Object.defineProperties(generator, {
40
		activeCount: {
41
			get: () => activeCount
42
		},
43
		pendingCount: {
44
			get: () => queue.length
45
		},
46
		clearQueue: {
47
			value: () => {
48
				queue.length = 0;
49
			}
50
		}
51
	});
52

    
53
	return generator;
54
};
55

    
56
module.exports = pLimit;
57
module.exports.default = pLimit;
(2-2/5)