Created
December 18, 2015 12:35
-
-
Save bloodyowl/78ba37eca4baf20d526c to your computer and use it in GitHub Desktop.
fetchURL.js
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
fetchURL("/").then(({ responseText }) => console.log(responseText)) | |
const request = fetchURL("/") | |
request.cancel() | |
request.then(() => console.log("NOT HAPPENING")) |
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
/** | |
* 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