UNPKG

@studyportals/sp-hs-misc

Version:

Miscellaneous code used in HouseStark's projects

87 lines 2.75 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; 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 { 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; } execute() { return __awaiter(this, void 0, void 0, function* () { yield 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); } executeActionAndSetOutcome() { return __awaiter(this, void 0, void 0, function* () { try { this._result = yield this.actionFn(); } catch (e) { this._error = e; } }); } setExecutedFlag() { this._executed = true; } } exports.Throttleable = Throttleable; //# sourceMappingURL=throttleable.class.js.map