UNPKG

vtils

Version:

一个面向业务的 JavaScript/TypeScript 实用程序库。

45 lines (44 loc) 1.11 kB
"use strict"; exports.__esModule = true; exports.asyncLimit = asyncLimit; /** * 异步函数并行执行限制。 * * @param asyncFn 异步函数 * @param options 选项 */ function asyncLimit(asyncFn, options) { if (options === void 0) { options = {}; } var _options = options, _options$concurrency = _options.concurrency, concurrency = _options$concurrency === void 0 ? 1 : _options$concurrency; var queue = []; var activeCount = 0; var call = function call() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return new Promise(function (resolve) { queue.push([args, resolve]); run(); }); }; var run = function run() { if (activeCount < concurrency && queue.length) { activeCount++; var _ref = queue.shift(), _args = _ref[0], _resolve = _ref[1]; var _res = asyncFn.apply(void 0, _args); _resolve(_res); _res.then(next, next); } }; var next = function next() { activeCount--; run(); }; return call; }