Skip to content

Instantly share code, notes, and snippets.

@ccnokes
Last active March 24, 2020 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccnokes/3fccba05d2ee31e7819bac2d3a5921e5 to your computer and use it in GitHub Desktop.
Save ccnokes/3fccba05d2ee31e7819bac2d3a5921e5 to your computer and use it in GitHub Desktop.
Minimal AbortController implementation for node.js that doesn't have to shim DOM stuff
import { EventEmitter } from 'events';
class AbortSignal {
private events = new EventEmitter();
constructor(
private getIsAborted: () => boolean
) {}
get aborted(): boolean {
return this.getIsAborted();
}
addEventListener(event: 'abort', fn: () => void) {
this.events.once(event, fn);
}
removeEventListener(event: 'abort', fn: () => void) {
this.events.removeListener(event, fn);
}
}
class AbortController {
private events = new EventEmitter();
private isAborted = false;
readonly signal: AbortSignal;
constructor() {
this.signal = new AbortSignal(() => this.isAborted)
}
abort() {
if (!this.isAborted) {
this.isAborted = true;
this.events.emit('abort');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment