Skip to content

Instantly share code, notes, and snippets.

@OliverJAsh
Last active August 30, 2017 10:01
Show Gist options
  • Save OliverJAsh/7d8e607742c46944dd32d0cf353c0632 to your computer and use it in GitHub Desktop.
Save OliverJAsh/7d8e607742c46944dd32d0cf353c0632 to your computer and use it in GitHub Desktop.
Cancellable fetch
type CancellableFetchResult = { aborted: true } | { aborted: false; responseText: string };
export type CancellableFetchReturn = {
completePromise: Promise<CancellableFetchResult>;
abort: Function;
};
// Returns a promise API and the original XHR for abortion.
export const cancellableFetch = (
url: string,
options: RequestInit = {},
): CancellableFetchReturn => {
const xhr = new XMLHttpRequest();
const completePromise = new Promise<CancellableFetchResult>((resolve, reject) => {
xhr.addEventListener('error', () => {
reject(new Error('XHR error'));
});
xhr.addEventListener('abort', () => {
resolve({ aborted: true });
});
xhr.addEventListener('load', () => {
resolve({ aborted: false, responseText: xhr.responseText });
});
const method = options.method !== undefined ? options.method : 'GET';
xhr.open(method, url, true);
xhr.send();
});
const abort = () => xhr.abort();
return { completePromise, abort };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment