Last active
March 24, 2020 20:46
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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