UNPKG

util-helpers

Version:

一个基于业务场景的工具方法库

57 lines (54 loc) 1.88 kB
'use strict'; var ConcurrencyController = (function () { function ConcurrencyController(maxConcurrency) { if (maxConcurrency === void 0) { maxConcurrency = 2; } this.maxConcurrency = Math.max(maxConcurrency, 1); this.runningCount = 0; this.queue = []; this.isPaused = false; } ConcurrencyController.prototype.add = function (task) { var _this = this; return new Promise(function (resolve, reject) { _this.queue.push({ task: task, resolve: resolve, reject: reject }); _this._run(); }); }; ConcurrencyController.prototype._run = function () { var _this = this; if (this.isPaused) return; while (this.runningCount < this.maxConcurrency && this.queue.length > 0) { var _a = this.queue.shift(), task = _a.task, resolve = _a.resolve, reject = _a.reject; this.runningCount++; task() .then(resolve) .catch(reject) .finally(function () { _this.runningCount--; _this._run(); }); } }; ConcurrencyController.prototype.getStatus = function () { return { running: this.runningCount, waiting: this.queue.length, maxConcurrency: this.maxConcurrency, paused: this.isPaused }; }; ConcurrencyController.prototype.setMaxConcurrency = function (maxConcurrency) { this.maxConcurrency = Math.max(maxConcurrency, 1); this._run(); }; ConcurrencyController.prototype.pause = function () { this.isPaused = true; }; ConcurrencyController.prototype.resume = function () { this.isPaused = false; this._run(); }; return ConcurrencyController; }()); module.exports = ConcurrencyController;