Last active
September 27, 2016 19:13
-
-
Save legalt/5c26f07e4e644c7e623575bf0252050d to your computer and use it in GitHub Desktop.
http XHR module
This file contains 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
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; |
This file contains 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
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