Skip to content

Instantly share code, notes, and snippets.

@stopsatgreen
Created March 9, 2015 10:28
Show Gist options
  • Save stopsatgreen/691a361be4953e132eda to your computer and use it in GitHub Desktop.
Save stopsatgreen/691a361be4953e132eda to your computer and use it in GitHub Desktop.
XHR with Promises
// Create new Promise
function get(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
// Then call it
get(reqURL).then(function (response) {
console.log(response);
}, function(error) {
console.error('Failed!', error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment