Skip to content

Instantly share code, notes, and snippets.

@legalt
Last active September 27, 2016 19:13
Show Gist options
  • Save legalt/5c26f07e4e644c7e623575bf0252050d to your computer and use it in GitHub Desktop.
Save legalt/5c26f07e4e644c7e623575bf0252050d to your computer and use it in GitHub Desktop.
http XHR module
function http ( url, config ) {
var xhr = new XMLHttpRequest(),
promise = {
success: function () {},
error: function () {}
};
config = config || {};
config.async = config.async || true;
config.method = config.method || 'GET';
config.data = config.data || '';
url = url || '/';
xhr.open(config.method, url, config.async);
xhr.send(config.data);
if ( config.async ) {
xhr.onreadystatechange = function() { // (3)
if (xhr.readyState != 4) return;
if ( xhr.status !== 200 ) {
promise.error({
status: xhr.status,
error: xhr.statusText
});
} else {
promise.success({
status: 200,
response: xhr.responseText
});
}
}
} else {
if ( xhr.status !== 200 ) {
promise.error({
status: xhr.status,
error: xhr.statusText
});
} else {
promise.success({
status: 200,
response: xhr.responseText
});
}
}
return {
then: function ( success, error ) {
promise.success = success;
promise.error = error;
}
};
}
//public
module.exports = http;
var http = require('./http');
http('http://jsonplaceholder.typicode.com/posts/1', {}).then(function successHandler( response ) {
console.log(response);
}, function errorHandler( response ) {
console.error(response);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment