UNPKG

@freemework/common

Version:

Common library of the Freemework Project.

92 lines 3.14 kB
import { FCancellationException } from "../cancellation/index.js"; import { FException, FExceptionAggregate } from "../exception/index.js"; export 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 = 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 = FException.wrapIfNeeded(e); errors.push(ex); }); })) .then(function () { if (errors.length > 0) { for (const error of errors) { if (!(error instanceof FCancellationException)) { throw new 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 FCancellationException)) { throw new 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() { } } //# sourceMappingURL=FChannelEventBase.js.map