public
Last active

XMLHttpRequest wrapped into a promise

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
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;
}

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 e.target.response not e.target.result

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.