Created
October 4, 2017 22:23
-
-
Save davepoon/c4a6663d7c9cc7601d8e800176728f67 to your computer and use it in GitHub Desktop.
Promise resolves after all the fetching is done
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 fetchAllTheRepos = (userName, repoCount) => { | |
const MAX_PER_PAGE = 100; | |
const baseUrl = 'https://api.github.com/users/' + userName + | |
'/repos?per_page=' + MAX_PER_PAGE; | |
//Start fetching every page of repos. | |
const fetchPromises = [], pageCount = Math.ceil(repoCount / | |
MAX_PER_PAGE); | |
for (let pageI = 1; pageI <= pageCount; ++pageI) { | |
const fetchPagePromise = fetch(baseUrl + '&page=' + pageI); | |
fetchPromises.push(fetchPagePromise); | |
} | |
//This promise resolves after all the fetching is done. | |
return Promise.all(fetchPromises) | |
.then((responses) => { | |
//Parse all the responses to JSON. | |
return Promise.all( responses.map((response) => response.json()) ); | |
}).then((results) => { | |
//Copy the results into one big array that has all the friggin repos. | |
let repos = []; | |
results.forEach((result) => { | |
repos = repos.concat(result); | |
}); | |
return repos; | |
}); | |
}; | |
//I left out the code to get the repo count, but that's pretty easy. | |
fetchAllTheRepos('erikh2000', 7).then((repos) => { | |
console.log(repos.length); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment