Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@KCreate
Last active April 25, 2016 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KCreate/f308875040501b900e327ce01f065908 to your computer and use it in GitHub Desktop.
Save KCreate/f308875040501b900e327ce01f065908 to your computer and use it in GitHub Desktop.
xhr request wrapper
export default function get(url, method, options, _callback) {
// Allow the options to be optional
if (typeof options == 'function') {
_callback = options;
options = {};
}
// Wrap the _callback
const callback = function(err) {
_callback(err, this.responseText);
}
// standard XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
// Curry the callback
xhr.addEventListener('load', callback.bind(xhr, null), false);
xhr.addEventListener('abort', callback.bind(xhr, xhr), false);
xhr.send(options);
// Abort after a timeout of 20 seconds or use the value set in the options
setTimeout(() => {
xhr.abort();
}, options.timeout || 20000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment