Last active
April 1, 2023 13:44
-
-
Save tjunghans/0129439ad12b37b98c72477156cddbce to your computer and use it in GitHub Desktop.
Example of an asynchronous function that returns a promise which can be cancelled using the AbortController
This file contains 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
// The implementation below is inspired by the [example](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal#examples) | |
// that shows how a fetch operation can be aborted using the signal option. | |
// See https://gist.github.com/tjunghans/da50cc29f3f965d587db99c2f44813f1 for an example on how `doSomethingAsync` is used. | |
function doSomethingAsync( | |
// payload can be anything. It's just an example | |
payload, | |
{ signal }: { signal?: AbortSignal } = {} | |
): Promise<any> { | |
// Abort immediately if `abort` was already called. | |
// The definition of `AbortException` is further down. | |
if (signal?.aborted) { | |
return Promise.reject(new AbortException()); | |
} | |
// Using a promise, but it could also be a callback. | |
return new Promise((resolve, reject) => { | |
// Create the handler with the call to reject | |
const abortHandler = () => { | |
reject(new AbortException()); | |
}; | |
// setTimeout is used as an example of an async operation. | |
setTimeout(() => { | |
// Remove the event handler on success. | |
signal?.removeEventListener("abort", abortHandler); | |
resolve(payload); | |
}, 1000); | |
// Add the signal abort handler | |
signal?.addEventListener("abort", abortHandler); | |
}); | |
} | |
// AbortException would normally live in its own file. | |
class AbortException extends DOMException { | |
constructor() { | |
super("Aborted", "AbortError"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment