Created
November 18, 2016 00:03
-
-
Save machuga/54966981c3720b04b799a7b1acb3581a to your computer and use it in GitHub Desktop.
Promise Example for Promise Talk
This file contains 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
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