UNPKG

villa

Version:

Promise utilities for async/await-ready environment.

78 lines 2.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const 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(resolve => 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 = {}) { return tslib_1.__awaiter(this, void 0, void 0, function* () { let { limit = 3, interval = 0 } = options; let lastError; for (let i = 0; i < limit; i++) { try { return yield handler(lastError, i); } catch (error) { lastError = error; } yield sleep(interval); } throw lastError; }); } exports.retry = retry; /** * BatchScheduler provides the ability to handle tasks scheduled within a time * span in batch. */ class BatchScheduler { /** * 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. */ constructor(handler, timeBeforeStart) { this.handler = handler; this.timeBeforeStart = timeBeforeStart; this.tasks = []; } /** Schedule a task. */ schedule(task) { return tslib_1.__awaiter(this, void 0, void 0, function* () { this.tasks.push(task); if (!this.batchPromise) { this.batchPromise = (this.timeBeforeStart ? sleep(this.timeBeforeStart) : Promise.resolve()).then(() => { let tasks = this.tasks; this.tasks = []; this.batchPromise = undefined; return this.handler(tasks); }); } return this.batchPromise; }); } } exports.BatchScheduler = BatchScheduler; //# sourceMappingURL=miscellaneous.js.map