Skip to content

Instantly share code, notes, and snippets.

@queerviolet
Last active February 9, 2025 15:33
Show Gist options
  • Save queerviolet/7aac570acfb6d6a50cc5 to your computer and use it in GitHub Desktop.
Save queerviolet/7aac570acfb6d6a50cc5 to your computer and use it in GitHub Desktop.
Github API demo with "class" functions and Promises
<!doctype html>
<html>
<head>
<title>Github User search</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src=github-user.js></script>
</head>
<body>
<form class=search-form>
<input name=query type=search>
</form>
</body>
</html>
/**** Model ****/
function GithubUser(params) {
for (p in params) {
this[p] = params[p];
}
}
GithubUser.prototype.getAvatar = function() {
var img = new Image();
img.src = this.avatar_url;
return img;
};
GithubUser.findByUsername = function(username) {
var deferred = $.get('https://api.github.com/users/' + username, {dataType: 'json'});
var promise = Promise.resolve(deferred);
return promise.then(function(response) {
// this GithubUser gets returned, and the promise routes it...
return new GithubUser(response);
});
}
/*** View ****/
document.addEventListener('submit', function(evt) {
evt.preventDefault();
alert(evt.target.query.value);
var username = evt.target.query.value;
GithubUser.findByUsername(username)
.then(function(user) {
// ...to here, as user (the arg to this function).
console.log(user);
document.body.appendChild(user.getAvatar());
})
.catch(function(error) {
// Any errors on lines 14, 17, 18, 30, or 31 end up here.
alert(JSON.stringify(error));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment