Skip to content

Instantly share code, notes, and snippets.

@machuga
Last active November 18, 2016 02:25
Show Gist options
  • Save machuga/1e3f2447c585e926308a0b4ba949cf68 to your computer and use it in GitHub Desktop.
Save machuga/1e3f2447c585e926308a0b4ba949cf68 to your computer and use it in GitHub Desktop.
Callback Example for Promise Talk
const githubApi = 'https://api.github.com';
const githubEventUrl = githubApi + '/users/machuga/events';
fetchReposForLatestActivity('machuga', console.log);
function fetchReposForLatestActivity(user, fn) {
request(githubEventsUrlFor(user), function(allEvents) {
fetchRepos(getThreeEvents(allEvents), function(rawRepos) {
fn(rawRepos.map(getRepo));
});
});
}
function fetchRepos(events, fn) {
var completedCount = 0;
var repos = [];
events.forEach(function(e) {
request(githubRepoUrlFor(e.repo.name), function(data) {
repos.push(data);
completedCount += 1;
if (completedCount === events.length) {
fn(repos);
}
});
});
}
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) {
$.getJSON(url, fn);
}
const githubApi = 'https://api.github.com';
// Do things, then output results to dev console
fetchReposForLatestActivity('machuga')
.then(console.log)
.catch(function(err) {
console.error(err.stack);
throw errl
}).then(function(x) {
console.log("You won't see this if you re-throw");
});
function request(url) {
return new Promise(function(resolve, reject) {
$.ajax({
url,
dataType: 'json'
}).then(resolve).fail(function() {
reject(new Error('Shit broke'));
})
});
}
// Function to kickoff
function fetchReposForLatestActivity(user) {
return request(githubEventsUrlFor(user))
.then(getThreeEvents)
.then(fetchRepos)
.then(function(rawRepos) {
return rawRepos.map(getRepo);
});
}
// Perform actions, wait for all to end
function fetchRepos(events) {
return Promise.all(events.map(fetchRepo));
}
function fetchRepo(event) {
return request(githubRepoUrlFor(event.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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment