1
0
Fork 0
management/front/dkha-web-sz-main/node_modules/p-limit/index.js

58 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

2023-12-18 13:12:25 +08:00
'use strict';
const pTry = require('p-try');
2024-01-16 21:26:16 +08:00
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'));
2023-12-18 13:12:25 +08:00
}
const queue = [];
let activeCount = 0;
const next = () => {
activeCount--;
if (queue.length > 0) {
queue.shift()();
}
};
2024-01-16 21:26:16 +08:00
const run = (fn, resolve, ...args) => {
activeCount++;
2023-12-18 13:12:25 +08:00
2024-01-16 21:26:16 +08:00
const result = pTry(fn, ...args);
resolve(result);
result.then(next, next);
};
const enqueue = (fn, resolve, ...args) => {
2023-12-18 13:12:25 +08:00
if (activeCount < concurrency) {
2024-01-16 21:26:16 +08:00
run(fn, resolve, ...args);
2023-12-18 13:12:25 +08:00
} else {
2024-01-16 21:26:16 +08: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;
}
2023-12-18 13:12:25 +08:00
}
});
2024-01-16 21:26:16 +08:00
return generator;
2023-12-18 13:12:25 +08:00
};
2024-01-16 21:26:16 +08:00
module.exports = pLimit;
module.exports.default = pLimit;