UNPKG

t-comm

Version:

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

88 lines (84 loc) 2.52 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var Scheduler = /** @class */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(maxConcurrency) { if (maxConcurrency === void 0) { maxConcurrency = 2; } var _this = this; this.doJob = function () { if (_this.doingJobs < _this.maxConcurrency && _this.pendingState.length) { _this.doingJobs += 1; var job_1 = _this.pendingState.shift(); if (!job_1) { return; } job_1().then(function (res) { var _a; _this.doingJobs -= 1; (_a = job_1.resolve) === null || _a === void 0 ? void 0 : _a.call(job_1, res); _this.doJob(); })["catch"](function (e) { var _a; _this.doingJobs -= 1; (_a = job_1.reject) === null || _a === void 0 ? void 0 : _a.call(job_1, e); _this.doJob(); })["finally"](function () {}); } }; this.pendingState = []; this.doingJobs = 0; this.maxConcurrency = maxConcurrency; } Scheduler.prototype.add = function (promiseCreator) { var _this = this; return new Promise(function (resolve, reject) { // 关键是给传过来的函数加个回调属性,当resolved的时候,就能返回对应的结果了。 promiseCreator.resolve = resolve; promiseCreator.reject = reject; _this.pendingState.push(promiseCreator); _this.doJob(); }); }; Scheduler.prototype.unshift = function (promiseCreator) { var _this = this; return new Promise(function (resolve, reject) { // 关键是给传过来的函数加个回调属性,当resolved的时候,就能返回对应的结果了。 promiseCreator.resolve = resolve; promiseCreator.reject = reject; _this.pendingState.unshift(promiseCreator); _this.doJob(); }); }; return Scheduler; }(); exports.Scheduler = Scheduler;