Last active
October 28, 2016 14:01
-
-
Save marcusshepp/93b429cc3d71a7154abef203887d226a to your computer and use it in GitHub Desktop.
js ajax promise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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