Last active
April 25, 2016 21:27
-
-
Save KCreate/f308875040501b900e327ce01f065908 to your computer and use it in GitHub Desktop.
xhr request wrapper
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
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