Skip to content

Instantly share code, notes, and snippets.

@liamnewmarch
Created July 29, 2021 17:48
Show Gist options
  • Save liamnewmarch/cb633182ae89e64751ef49676afb70a8 to your computer and use it in GitHub Desktop.
Save liamnewmarch/cb633182ae89e64751ef49676afb70a8 to your computer and use it in GitHub Desktop.
Promise subclass which uses AbortController to provide a cancel() method.
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