Simple HTTP request as Promise
function http(options) {
var deferred = q.defer(),
req = new XMLHttpRequest();
if (!options.url) {
throw new Error('No url given');
} else {
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.response);
}
};
req.send(options.data || void 0);
return deferred.promise;
}
With friendly support from Matthew Phillips:
https://gist.github.com/matthewp/3099268
Written by Dimitri
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Js
Authors
Related Tags
#js
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#