Skip to content

Instantly share code, notes, and snippets.

@marcusshepp
Last active October 28, 2016 14:01
Show Gist options
  • Save marcusshepp/93b429cc3d71a7154abef203887d226a to your computer and use it in GitHub Desktop.
Save marcusshepp/93b429cc3d71a7154abef203887d226a to your computer and use it in GitHub Desktop.
js ajax promise
function ajax(type, url){
return new Promise(function(resolve, reject){
var http_request = new XMLHttpRequest();
http_request.open(type, "http://127.0.0.1:8000/"+ url);
http_request.onload = function() {
if (http_request.status === 200){
resolve(JSON.parse(http_request.response));
} else {
reject(Error(http_request.statusText));
}
};
http_request.onerror = function(){
reject(Error("network error"));
};
http_request.send();
});
}
// to use
ajax("GET", "api/articles/")
.then(function(articles){
this.setState({ articles });
}.bind(this),
function(error){
console.log("REJECT");
console.log(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment