Skip to content
Create a gist now

Instantly share code, notes, and snippets.

XMLHttpRequest wrapped into a promise
function xhr(options) {
var deferred = Q.defer(),
req = new XMLHttpRequest(); || 'GET', options.url, true);
// Set request headers if provided.
Object.keys(options.headers || {}).forEach(function (key) {
req.setRequestHeader(key, options.headers[key]);
req.onreadystatechange = function(e) {
if(req.readyState !== 4) {
if([200,304].indexOf(req.status) === -1) {
deferred.reject(new Error('Server responded with a status of ' + req.status));
} else {
req.send( || void 0);
return deferred.promise;
domenic commented Jul 12, 2012

You should reject with Error instances, just like you throw with them :)


Good point, but isn't this something Q should handle internally?


You mean not

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.