UNPKG

@studyportals/sp-hs-misc

Version:

Miscellaneous code used in HouseStark's projects

79 lines 1.96 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Throttleable = void 0; /** * Aggregates an action whose execution can be deffered and offers the * necessary functionality to notify observers when the action had been * executed, providing the outcome. */ class Throttleable { _actionFn; _observers; _result; _error; _executed; get actionFn() { return this._actionFn; } get observers() { return this._observers; } get result() { return this._result; } get error() { return this._error; } get executed() { return this._executed; } constructor(actionFn) { this._observers = []; this._actionFn = actionFn; this._result = null; this._error = null; this._executed = false; } async execute() { await this.executeActionAndSetOutcome(); this.setExecutedFlag(); this.notifyObservers(); } observe(observerFn) { if (this.executed) { this.notifyObserver(observerFn); } else { this.addObserver(observerFn); } } createObservingPromise() { return new Promise((resolve, reject) => { this.observe((err, res) => err ? reject(err) : resolve(res)); }); } notifyObservers() { for (let observer of this.observers) { this.notifyObserver(observer); } } notifyObserver(observer) { observer(this.error, this.result); } addObserver(observer) { this.observers.push(observer); } async executeActionAndSetOutcome() { try { this._result = await this.actionFn(); } catch (e) { this._error = e; } } setExecutedFlag() { this._executed = true; } } exports.Throttleable = Throttleable; //# sourceMappingURL=throttleable.class.js.map