Created
July 7, 2023 15:51
-
-
Save ferdaber/203340e41924b5b4d478d2404789f8f7 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
export class AbortablePromise<T> extends Promise<T> { | |
#aborted = false; | |
abort() { | |
this.#aborted = true; | |
} | |
then<TResult1 = T, TResult2 = never>( | |
onfulfilled?: | |
| ((value: T) => TResult1 | PromiseLike<TResult1>) | |
| null | |
| undefined, | |
onrejected?: | |
| ((reason: any) => TResult2 | PromiseLike<TResult2>) | |
| null | |
| undefined | |
): Promise<TResult1 | TResult2> { | |
return super.then( | |
(value) => { | |
if (this.#aborted) { | |
// create new promises each time so that everything can be GC'd correctly | |
return new Promise<TResult1>(() => { | |
/* never fulfill */ | |
}); | |
} else if (onfulfilled) { | |
return onfulfilled(value); | |
} else { | |
return value as any; | |
} | |
}, | |
(reason) => { | |
if (this.#aborted) { | |
// create new promises each time so that everything can be GC'd correctly | |
return new Promise<TResult2>(() => { | |
/* never fulfill */ | |
}); | |
} else if (onrejected) { | |
return onrejected(reason); | |
} else { | |
throw reason; | |
} | |
} | |
); | |
} | |
// `catch` and `finally` both internally call `then`, so only `then` needs to be overridden | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment