@freemework/common
Version:
Common library of the Freemework Project.
59 lines • 2 kB
JavaScript
import { FException, FExceptionAggregate } from "../exception/index.js";
/**
* Wrap several tokens as FCancellationToken
*/
export class FCancellationTokenAggregated {
_innerTokens;
_cancelListeners = [];
_isCancellationRequested;
constructor(...tokens) {
this._innerTokens = tokens;
this._isCancellationRequested = false;
const listener = (cancellationEx) => {
for (const innerToken of tokens) {
innerToken.removeCancelListener(listener);
}
this._isCancellationRequested = true;
const errors = [];
if (this._cancelListeners.length > 0) {
// Release callback. We do not need its anymore
const cancelListeners = this._cancelListeners.splice(0);
cancelListeners.forEach(cancelListener => {
try {
cancelListener(cancellationEx);
}
catch (e) {
errors.push(FException.wrapIfNeeded(e));
}
});
}
if (errors.length > 0) {
throw new FExceptionAggregate(errors);
}
};
for (const innerToken of tokens) {
innerToken.addCancelListener(listener);
}
}
/**
* Returns `true` if any of inner tokens requested cancellation
*/
get isCancellationRequested() {
return this._isCancellationRequested;
}
addCancelListener(cb) {
this._cancelListeners.push(cb);
}
removeCancelListener(cb) {
const cbIndex = this._cancelListeners.indexOf(cb);
if (cbIndex !== -1) {
this._cancelListeners.splice(cbIndex, 1);
}
}
throwIfCancellationRequested() {
for (const innerToken of this._innerTokens) {
innerToken.throwIfCancellationRequested();
}
}
}
//# sourceMappingURL=f_cancellation_token_aggregated.js.map