@freemework/common
Version:
Common library of the Freemework Project.
57 lines • 2.05 kB
JavaScript
import { FException, FExceptionAggregate } from "../exception/index.js";
import { FCancellationException } from "./f_cancellation_exception.js";
export class FCancellationTokenSourceManual {
_token;
_cancelListeners = [];
_isCancellationRequested;
constructor() {
this._isCancellationRequested = false;
const self = this;
this._token = {
get isCancellationRequested() { return self.isCancellationRequested; },
addCancelListener(cb) { self.addCancelListener(cb); },
removeCancelListener(cb) { self.removeCancelListener(cb); },
throwIfCancellationRequested() { self.throwIfCancellationRequested(); }
};
}
get token() { return this._token; }
get isCancellationRequested() { return this._isCancellationRequested; }
cancel() {
if (this._isCancellationRequested) {
// Prevent to call listeners twice
return;
}
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();
}
catch (e) {
errors.push(FException.wrapIfNeeded(e));
}
});
}
if (errors.length > 0) {
throw new FExceptionAggregate(errors);
}
}
addCancelListener(cb) {
this._cancelListeners.push(cb);
}
removeCancelListener(cb) {
const cbIndex = this._cancelListeners.indexOf(cb);
if (cbIndex !== -1) {
this._cancelListeners.splice(cbIndex, 1);
}
}
throwIfCancellationRequested() {
if (this.isCancellationRequested) {
throw new FCancellationException();
}
}
}
//# sourceMappingURL=f_cancellation_token_source_manual.js.map