Skip to content

Instantly share code, notes, and snippets.

@matthewp
Created July 12, 2012 16:50
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save matthewp/3099268 to your computer and use it in GitHub Desktop.
Save matthewp/3099268 to your computer and use it in GitHub Desktop.
XMLHttpRequest wrapped into a promise
function xhr(options) {
var deferred = Q.defer(),
req = new XMLHttpRequest();
req.open(options.method || '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) {
return;
}
if([200,304].indexOf(req.status) === -1) {
deferred.reject(new Error('Server responded with a status of ' + req.status));
} else {
deferred.resolve(e.target.result);
}
};
req.send(options.data || void 0);
return deferred.promise;
}
@domenic
Copy link

domenic commented Jul 12, 2012

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

@matthewp
Copy link
Author

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

@nathanboktae
Copy link

You mean e.target.response not e.target.result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment