Last active
July 9, 2026 07:36
-
-
Save benhatsor/c9ac377ef4deb573a77aace20101fb8e to your computer and use it in GitHub Desktop.
Abortable Promise
This file contains hidden or 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
| /** | |
| * Abortable Promise | |
| * @remarks | |
| * Call {@linkcode abort abort(reason?:)} to abort the signal and resolve the promise. | |
| */ | |
| export class AbortablePromise extends AbortController { | |
| promise: Promise<typeof this.signal.reason> | |
| // Bind method to allow destructuring | |
| // (see: https://stackoverflow.com/a/10743608) | |
| override abort = super.abort.bind(this) | |
| constructor() { | |
| super() | |
| const { promise, resolve } = Promise.withResolvers<typeof this.signal.reason>() | |
| this.promise = promise | |
| // 'once' removes listener after invocation | |
| this.signal.addEventListener( | |
| 'abort', () => resolve(this.signal.reason), { once: true } | |
| ) | |
| } | |
| } | |
| // Alternate function version: | |
| function abortablePromise() { | |
| const abortController = new AbortController(), | |
| signal = abortController.signal, | |
| abort = abortController.abort.bind(abortController); | |
| const { promise, resolve } = Promise.withResolvers<typeof signal.reason>(); | |
| signal.addEventListener( | |
| 'abort', () => resolve(signal.reason), { once: true } | |
| ); | |
| return { promise, signal, abort }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment