UNPKG

villa

Version:

Promise utilities for async/await-ready environment.

99 lines 3.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); /** * A no-operation function that acts as the rejection handler of a promise. */ function bear(_error) { return; } exports.bear = bear; /** * Create a promise that will be fulfilled in given duration (milliseconds). * @param duration Duration in milliseconds before the promise gets fulfilled. */ function sleep(duration) { return new Promise(function (resolve) { return setTimeout(resolve, duration); }); } exports.sleep = sleep; /** * Retry procedure in the handler for several times. * @param handler Retry handler. * @param options Retry options. * @return Created promise. */ function retry(handler, options) { if (options === void 0) { options = {}; } return tslib_1.__awaiter(this, void 0, void 0, function () { var _a, limit, _b, interval, lastError, i, error_1; return tslib_1.__generator(this, function (_c) { switch (_c.label) { case 0: _a = options.limit, limit = _a === void 0 ? 3 : _a, _b = options.interval, interval = _b === void 0 ? 0 : _b; i = 0; _c.label = 1; case 1: if (!(i < limit)) return [3 /*break*/, 8]; _c.label = 2; case 2: _c.trys.push([2, 4, , 5]); return [4 /*yield*/, handler(lastError, i)]; case 3: return [2 /*return*/, _c.sent()]; case 4: error_1 = _c.sent(); lastError = error_1; return [3 /*break*/, 5]; case 5: return [4 /*yield*/, sleep(interval)]; case 6: _c.sent(); _c.label = 7; case 7: i++; return [3 /*break*/, 1]; case 8: throw lastError; } }); }); } exports.retry = retry; /** * BatchScheduler provides the ability to handle tasks scheduled within a time * span in batch. */ var BatchScheduler = /** @class */ (function () { /** * Construct a BatchScheduler instance. * * @param handler A batch handler for the tasks put together. * @param timeBeforeStart The time span within which tasks would be handled * in batch. */ function BatchScheduler(handler, timeBeforeStart) { this.handler = handler; this.timeBeforeStart = timeBeforeStart; this.tasks = []; } /** Schedule a task. */ BatchScheduler.prototype.schedule = function (task) { return tslib_1.__awaiter(this, void 0, void 0, function () { var _this = this; return tslib_1.__generator(this, function (_a) { this.tasks.push(task); if (!this.batchPromise) { this.batchPromise = (this.timeBeforeStart ? sleep(this.timeBeforeStart) : Promise.resolve()).then(function () { var tasks = _this.tasks; _this.tasks = []; _this.batchPromise = undefined; return _this.handler(tasks); }); } return [2 /*return*/, this.batchPromise]; }); }); }; return BatchScheduler; }()); exports.BatchScheduler = BatchScheduler; //# sourceMappingURL=miscellaneous.js.map