I'm working on an Angular.js app which makes some calls to the GitHub API. First, a call is made to retrieve all the repos for a user. Then for each repo, a call is made to retrieve the README. I have a javascript function which I would like to be run only after all the README API calls are completed.
Here is my controller:
readmeSearch.controller('ReadMeSearchController', ['RepoSearch', 'ReadMeSearch', function(RepoSearch, ReadMeSearch) {
var self = this;
self.gitRepoNames = [];
self.readMes = [];
self.noReadMes = [];
self.doSearch = function() {
RepoSearch.query(self.username)
.then(function(repoResponse) {
addRepoNames(repoResponse);
for(var i = 0; i< self.gitRepoNames.length; i++) {
(function(i) {
ReadMeSearch.query(self.username, self.gitRepoNames[i])
.then(function(readMeResponse) {
addToReposWithReadMes(readMeResponse, i);
}).catch(function(e){
addToReposWithoutReadMes(repoResponse, i);
});
})(i);
};
});
};
addRepoNames = function(response) {
self.searchResult = response.data;
for(var i = 0; i < self.searchResult.length; i++) {
var name = self.searchResult[i]['name']
self.gitRepoNames.push(name);
};
};
addToReposWithReadMes = function(response, i) {
self.readMes.push(
{
name: self.gitRepoNames[i],
size: parseInt(response.data["size"]),
url: response.data["html_url"]
}
);
};
addToReposWithoutReadMes = function(response, i) {
self.noReadMes.push(
{
name: self.gitRepoNames[i]
}
);
};
percentageOfReposWithReadMes = function() {
var percentage;
percentage = (self.noReadMes.length / self.gitRepoNames.length) * 100
self.readMePercentage = percentage.toFixed(1);
};
}]);
The README API calls using the ReadMeSearch factory populate two arrays, one for repos with READMEs and one for repos without READMEs. I would like to run the function percentageOfReposWithReadMes
only after the ReadMeSearch.query
has been completed for all the repos in self.gitRepoNames
.
I've tried using .then
after the RepoSearch.query
but this doesn't seem to work. I think I'm a bit muddled in my understanding of Angular promises and the .then
function. Any help would be greatly appreciated.