staggerjs
Version:
Light utility to stagger a stack of async methods
74 lines (55 loc) • 2.16 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _tcomb = require('tcomb');
var _tcomb2 = _interopRequireDefault(_tcomb);
var _throttleFunction = require('throttle-function');
var _throttleFunction2 = _interopRequireDefault(_throttleFunction);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var InfinityType = _tcomb2.default.irreducible('InfinityType', function (x) {
return typeof x === 'number' && x === Infinity;
});
var Methods = _tcomb2.default.list(_tcomb2.default.Function);
var Settings = _tcomb2.default.interface({
perSecond: _tcomb2.default.union([_tcomb2.default.Number, InfinityType]),
maxOngoingMethods: _tcomb2.default.union([_tcomb2.default.Integer, InfinityType])
}, { strict: true });
var defaultSettings = {
perSecond: 20,
maxOngoingMethods: 5
};
exports.default = function (_methods, _settings) {
var methods = Methods(_methods);
var settings = Settings(_extends({}, defaultSettings, _settings));
var maxOngoingMethods = settings.maxOngoingMethods,
perSecond = settings.perSecond;
var throttle = (0, _throttleFunction2.default)(function (method) {
return method();
}, {
window: 1, // window is in seconds
limit: perSecond
});
return new Promise(function (resolve) {
var queue = [];
var onDone = function onDone(res) {
throttle(function () {
return runMethod(methods[queue.length]);
});
return res;
};
var runMethod = function runMethod(method) {
if (queue.length !== methods.length) {
queue.push(method().then(onDone).catch(onDone));
} else {
resolve(Promise.all(queue));
}
};
methods.slice(0, maxOngoingMethods).forEach(function (m, i) {
return i === 0 ? runMethod(m) : throttle(function () {
return runMethod(m);
});
});
});
};