UNPKG

@newdash/newdash

Version:

javascript/typescript utility library

50 lines (49 loc) 1.54 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.synchronized = exports.limit = void 0; const assert_1 = require("../assert"); const defineFunctionName_1 = __importDefault(require("../functional/defineFunctionName")); const Semaphore_1 = require("../functional/Semaphore"); /** * limit concurrent for parallel operations * * @category Async * @since 5.15.0 * @param runner async operation function * @param concurrencyNumber max concurrency number * * @returns the concurrency limited function wrapper * */ function limit(runner, concurrencyNumber) { (0, assert_1.mustProvide)(runner, "runner", "function"); (0, assert_1.mustProvide)(concurrencyNumber, "concurrencyNumber", "number"); const sem = new Semaphore_1.Semaphore(concurrencyNumber); // @ts-ignore return (0, defineFunctionName_1.default)(async (...args) => { const release = await sem.acquire(); try { return await runner(...args); } finally { release(); } }, runner?.name); } exports.limit = limit; /** * let async function only invoke at once in same time * * @category Async * @since 5.20.0 * @param func the function to be processed * @returns the wrapped function instance */ function synchronized(func) { return limit(func, 1); } exports.synchronized = synchronized; exports.default = limit;