Skip to content

Instantly share code, notes, and snippets.

@gsevla
Last active June 22, 2023 16:53
Show Gist options
  • Select an option

  • Save gsevla/631941a1fa9ca90ccf2de73cfd8ba63f to your computer and use it in GitHub Desktop.

Select an option

Save gsevla/631941a1fa9ca90ccf2de73cfd8ba63f to your computer and use it in GitHub Desktop.
promise cancellation
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