Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created December 18, 2015 12:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bloodyowl/78ba37eca4baf20d526c to your computer and use it in GitHub Desktop.
Save bloodyowl/78ba37eca4baf20d526c to your computer and use it in GitHub Desktop.
fetchURL.js
fetchURL("/").then(({ responseText }) => console.log(responseText))
const request = fetchURL("/")
request.cancel()
request.then(() => console.log("NOT HAPPENING"))
/**
* fetches a given URL through `XMLHttpRequest`.
* like `fetch` but cancellable.
*
* @param {string} url
* @param {object} [options]
* @param {string} [options.method=GET]
* @param {string} [options.body=null]
* @param {object} [options.headers={}]
* @param {boolean} [options.withCredentials=false]
* @returns {object}
*/
const fetchURL = (url, { method = "GET", body = null, headers = {}, withCredentials = false } = {}) => {
const xhr = new XMLHttpRequest()
return Object.assign(
new Promise((resolve, reject) => {
xhr.open(method, url, true)
Object.keys(headers).forEach((key) => {
xhr.setRequestHeader(key.toLowerCase(), headers[key])
})
xhr.withCredentials = withCredentials
xhr.onreadystatechange = () => {
if(xhr.readyState === 4 && xhr.status !== 0 && xhr.statusText !== "abort") {
resolve(xhr)
}
}
xhr.send(body)
}),
{
cancel: () => {
xhr.abort()
},
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment