Skip to content

Instantly share code, notes, and snippets.

@machuga
Created November 18, 2016 00:03
Show Gist options
  • Save machuga/54966981c3720b04b799a7b1acb3581a to your computer and use it in GitHub Desktop.
Save machuga/54966981c3720b04b799a7b1acb3581a to your computer and use it in GitHub Desktop.
Promise Example for Promise Talk
const githubApi = 'https://api.github.com';
const githubEventUrl = githubApi + '/users/machuga/events';
fetchReposForLatestActivity('machuga').then(console.log);
function fetchReposForLatestActivity(user, fn) {
return new Promise(function(resolve, reject) {
request(githubEventsUrlFor(user))
.then(getThreeEvents)
.then(fetchRepos)
.then(function(repos) {
resolve(repos.map(getRepo));
});
});
}
function fetchRepos(events, fn) {
return Promise.all(events.map(function(e) {
return request(githubRepoUrlFor(e.repo.name));
}));
}
function getRepo(repo) {
return {
author: repo.owner.login,
avatar: repo.owner.avatar_url,
name: repo.name,
full_name: repo.full_name,
url: repo.html_url,
description: repo.description
};
}
function getThreeEvents(events) {
return events.slice(0, 3);
}
function githubEventsUrlFor(user) {
return githubApi + '/users/'+user+'/events';
}
function githubRepoUrlFor(repo) {
return githubApi + '/repos/'+repo;
}
function log(a) {
console.log(a);
}
function request(url, fn) {
return Promise.resolve($.getJSON(url).then(fn));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment