@studyportals/sp-hs-misc
Version:
Miscellaneous code used in HouseStark's projects
71 lines • 1.77 kB
JavaScript
/**
* 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;
}
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;
}
}
export { Throttleable };
//# sourceMappingURL=throttleable.class.js.map