Skip to content

Instantly share code, notes, and snippets.

@benhatsor
Last active July 9, 2026 07:36
Show Gist options
  • Select an option

  • Save benhatsor/c9ac377ef4deb573a77aace20101fb8e to your computer and use it in GitHub Desktop.

Select an option

Save benhatsor/c9ac377ef4deb573a77aace20101fb8e to your computer and use it in GitHub Desktop.
Abortable Promise
/**
* 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