@naturalcycles/js-lib
Version:
Standard library for universal (browser + Node.js) javascript
33 lines (32 loc) • 735 B
JavaScript
/**
* Similar to AbortController and AbortSignal.
* Similar to pDefer and Promise.
* Similar to Subject and Observable.
*
* Minimal interface for something that can be aborted in the future,
* but not necessary.
* Allows to listen to `onAbort` event.
*
* @experimental
*/
export class Abortable {
onAbort;
constructor(onAbort) {
this.onAbort = onAbort;
}
aborted = false;
abort() {
if (this.aborted)
return;
this.aborted = true;
this.onAbort?.();
this.onAbort = undefined; // cleanup listener
}
clear() {
this.onAbort = undefined;
}
}
// convenience function
export function abortable(onAbort) {
return new Abortable(onAbort);
}