Last active
August 30, 2017 10:01
-
-
Save OliverJAsh/7d8e607742c46944dd32d0cf353c0632 to your computer and use it in GitHub Desktop.
Cancellable fetch
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
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