Last active
June 22, 2023 16:53
-
-
Save gsevla/631941a1fa9ca90ccf2de73cfd8ba63f to your computer and use it in GitHub Desktop.
promise cancellation
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
| function withCancellationSignal({asyncMethod, signal}) { | |
| const cancellationTask = new Promise((_, reject) => { | |
| const abortListener = ({target}) => { | |
| signal.removeEventListener('abort', abortListener); | |
| reject(target.reason) | |
| } | |
| signal.addEventListener('abort', abortListener) | |
| }) | |
| return Promise.race([ | |
| asyncMethod, | |
| cancellationTask | |
| ]) | |
| } | |
| async function thatWaitForAPromise() { | |
| ... | |
| await forSomething() | |
| ... | |
| } | |
| // usage | |
| const abortController = new AbortController() | |
| withCancellationSignal({ asyncMethod: thatWaitForAPromise, signal: abortController.signal }) // thatWaitForAPromise function running | |
| abortController.abort('I wanted to abort!') // cancellationTask win the race over asyncMethod |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment