Skip to content

Instantly share code, notes, and snippets.

@stuartc
Created October 18, 2014 15:01
Show Gist options
  • Save stuartc/6ca0dc530542af1ec81a to your computer and use it in GitHub Desktop.
Save stuartc/6ca0dc530542af1ec81a to your computer and use it in GitHub Desktop.
XMLHttpRequest wrapped in a promise
// request('GET',url)
// .then(console.log.bind(console))
// .catch(console.error.bind(console));
var request = function (verb,url,data) {
return new Promise(function (resolve,reject) {
var stateChange = function (xhr) {
request = xhr.target;
if (request.readyState !== 4) {
return
}
if ([200,304].indexOf(request.status) === -1) {
reject(request);
} else {
resolve(request.response);
}
};
var request = new XMLHttpRequest();
request.open(verb,url,true);
request.withCredentials = true;
request.onreadystatechange = stateChange;
request.setRequestHeader("Content-Type", "application/json");
request.setRequestHeader("Accept","application/json");
request.send(JSON.stringify(data));
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment