Skip to content

Instantly share code, notes, and snippets.

@umayr
Last active July 10, 2017 06:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umayr/59faffb805434b29517c to your computer and use it in GitHub Desktop.
Save umayr/59faffb805434b29517c to your computer and use it in GitHub Desktop.
Promise API example in native javascript
function getGithubUserInfo(username) {
return new Promise(function (resolve, reject) {
// Do the usual XHR stuff
var url = "https://api.github.com/users/" + username;
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function () {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function () {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
getGithubUserInfo("umayr")
.then(function (response) {
console.log("Success");
console.log(response);
bindResults(response);
}, function (error) {
console.error("Failed");
console.error(error);
bindResults(error);
});
function bindResults(result) {
var _pre = document.createElement('pre');
_pre.innerHTML = result;
document.body.appendChild(_pre);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment