UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

99 lines (92 loc) 3.09 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _classCallCheck = require('@babel/runtime/helpers/classCallCheck'); var _createClass = require('@babel/runtime/helpers/createClass'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck); var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass); var Scheduler = /*#__PURE__*/function () { /** * 异步任务调度器,同一时间只能执行 n 个任务 * @param {number} [maxConcurrency] 最多同时执行的任务数目,默认为 2 * * @example * ```ts * let scheduler; * * export async function login({ * userId, * userSig, * tim, * }: { * userId: string; * userSig: string; * tim: IChatSDK; * }) { * if (!scheduler) { * scheduler = new Scheduler(1); * } * * return await scheduler.add(innerLogin.bind(null, { * userId, * userSig, * tim, * })); * } * ``` */ function Scheduler() { var _this = this; var maxConcurrency = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2; _classCallCheck__default["default"](this, Scheduler); this.doJob = function () { if (_this.doingJobs < _this.maxConcurrency && _this.pendingState.length) { _this.doingJobs += 1; var job = _this.pendingState.shift(); if (!job) { return; } job().then(function (res) { var _a; _this.doingJobs -= 1; (_a = job.resolve) === null || _a === void 0 ? void 0 : _a.call(job, res); _this.doJob(); })["catch"](function (e) { var _a; _this.doingJobs -= 1; (_a = job.reject) === null || _a === void 0 ? void 0 : _a.call(job, e); _this.doJob(); })["finally"](function () {}); } }; this.pendingState = []; this.doingJobs = 0; this.maxConcurrency = maxConcurrency; } return _createClass__default["default"](Scheduler, [{ key: "add", value: function add(promiseCreator) { var _this2 = this; return new Promise(function (resolve, reject) { // 关键是给传过来的函数加个回调属性,当resolved的时候,就能返回对应的结果了。 promiseCreator.resolve = resolve; promiseCreator.reject = reject; _this2.pendingState.push(promiseCreator); _this2.doJob(); }); } }, { key: "unshift", value: function unshift(promiseCreator) { var _this3 = this; return new Promise(function (resolve, reject) { // 关键是给传过来的函数加个回调属性,当resolved的时候,就能返回对应的结果了。 promiseCreator.resolve = resolve; promiseCreator.reject = reject; _this3.pendingState.unshift(promiseCreator); _this3.doJob(); }); } }]); }(); exports.Scheduler = Scheduler;