Created
July 29, 2021 17:48
-
-
Save liamnewmarch/cb633182ae89e64751ef49676afb70a8 to your computer and use it in GitHub Desktop.
Promise subclass which uses AbortController to provide a cancel() method.
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
export class CancellablePromise extends Promise { | |
#abortController; | |
constructor(callback) { | |
const abortController = new AbortController(); | |
super((resolve, reject) => { | |
callback(resolve, reject); | |
abortController.signal.addEventListener('abort', reject); | |
}); | |
this.#abortController = abortController; | |
} | |
get abortSignal() { | |
return this.#abortController.signal; | |
} | |
cancel() { | |
this.#abortController.abort(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment