2017-12-15 10:56:14 -08:00
|
|
|
'use strict';
|
2021-05-08 05:39:21 -07:00
|
|
|
const pTry = require('p-try');
|
|
|
|
|
|
|
|
const pLimit = concurrency => {
|
|
|
|
if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
|
|
|
|
return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up'));
|
2017-12-15 10:56:14 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
const queue = [];
|
|
|
|
let activeCount = 0;
|
|
|
|
|
|
|
|
const next = () => {
|
|
|
|
activeCount--;
|
|
|
|
|
|
|
|
if (queue.length > 0) {
|
|
|
|
queue.shift()();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-05-08 05:39:21 -07:00
|
|
|
const run = (fn, resolve, ...args) => {
|
|
|
|
activeCount++;
|
|
|
|
|
|
|
|
const result = pTry(fn, ...args);
|
|
|
|
|
|
|
|
resolve(result);
|
|
|
|
|
|
|
|
result.then(next, next);
|
|
|
|
};
|
2017-12-15 10:56:14 -08:00
|
|
|
|
2021-05-08 05:39:21 -07:00
|
|
|
const enqueue = (fn, resolve, ...args) => {
|
2017-12-15 10:56:14 -08:00
|
|
|
if (activeCount < concurrency) {
|
2021-05-08 05:39:21 -07:00
|
|
|
run(fn, resolve, ...args);
|
2017-12-15 10:56:14 -08:00
|
|
|
} else {
|
2021-05-08 05:39:21 -07:00
|
|
|
queue.push(run.bind(null, fn, resolve, ...args));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
|
|
|
|
Object.defineProperties(generator, {
|
|
|
|
activeCount: {
|
|
|
|
get: () => activeCount
|
|
|
|
},
|
|
|
|
pendingCount: {
|
|
|
|
get: () => queue.length
|
|
|
|
},
|
|
|
|
clearQueue: {
|
|
|
|
value: () => {
|
|
|
|
queue.length = 0;
|
|
|
|
}
|
2017-12-15 10:56:14 -08:00
|
|
|
}
|
|
|
|
});
|
2021-05-08 05:39:21 -07:00
|
|
|
|
|
|
|
return generator;
|
2017-12-15 10:56:14 -08:00
|
|
|
};
|
2021-05-08 05:39:21 -07:00
|
|
|
|
|
|
|
module.exports = pLimit;
|
|
|
|
module.exports.default = pLimit;
|