@freemework/common
Version:
Common library of the Freemework Project.
96 lines • 3.33 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FChannelEventBase = void 0;
const index_js_1 = require("../cancellation/index.js");
const index_js_2 = require("../exception/index.js");
class FChannelEventBase {
_callbacks;
addHandler(cb) {
if (this._callbacks === undefined) {
this._callbacks = [];
}
this._callbacks.push(cb);
if (this._callbacks.length === 1) {
this.onAddFirstHandler();
}
}
removeHandler(cb) {
if (this._callbacks === undefined) {
return;
}
const index = this._callbacks.indexOf(cb);
if (index !== -1) {
this._callbacks.splice(index, 1);
if (this._callbacks.length === 0) {
this.onRemoveLastHandler();
}
}
}
constructor() {
this._callbacks = [];
}
notify(executionContext, event) {
if (this._callbacks === undefined || this._callbacks.length === 0) {
return Promise.resolve();
}
const callbacks = this._callbacks.slice();
if (callbacks.length === 1) {
const callback = callbacks[0];
return callback(executionContext, event);
}
const promises = [];
const errors = [];
for (const callback of callbacks) {
try {
const result = callback(executionContext, event);
promises.push(result);
}
catch (e) {
const ex = index_js_2.FException.wrapIfNeeded(e);
errors.push(ex);
}
}
if (promises.length === 1 && errors.length === 0) {
return promises[0];
}
else if (promises.length > 0) {
return Promise
.all(promises.map(function (p) {
return p.catch(function (e) {
const ex = index_js_2.FException.wrapIfNeeded(e);
errors.push(ex);
});
}))
.then(function () {
if (errors.length > 0) {
for (const error of errors) {
if (!(error instanceof index_js_1.FCancellationException)) {
throw new index_js_2.FExceptionAggregate(errors);
}
}
// So, all errors are FCancellationException instances, throw first
throw errors[0];
}
});
}
else {
if (errors.length > 0) {
for (const error of errors) {
if (!(error instanceof index_js_1.FCancellationException)) {
throw new index_js_2.FExceptionAggregate(errors);
}
}
// So, all errors are FCancellationException instances, throw first
throw errors[0];
}
else {
return Promise.resolve();
}
}
}
get hasSubscribers() { return this._callbacks !== undefined && this._callbacks.length > 0; }
onAddFirstHandler() { }
onRemoveLastHandler() { }
}
exports.FChannelEventBase = FChannelEventBase;
//# sourceMappingURL=FChannelEventBase.js.map