I want to download data for all of my repos from the Github API.
Github paginates their responses and includes a header Link type:"next"
when there's another page available. So I know I want to wait for all the pages to be received... but I don't know initially how many pages there are going to be, and I don't know if there's a next page until the one before it comes in.
So far I've got this, and it works:
var allRepos = [];
var repoPageReqs = [$.Deferred()]; // <-- sketchy
function receivedReposPage(data, status, req) {
//handle error inadequately but whatever for now
if (status !== "success") { console.log(data, status, req); return; }
console.log("Received repos from Github:", data);
for (i in data) {
allRepos.push(data[i]);
}
saveRepos(allRepos);
var headerLink = req.getResponseHeader("Link");
var headerLinkNext = parseLinkHeader(headerLink)["next"];
if (headerLinkNext) {
console.log("Following 'next' header link, collecting paginated repos.");
repoPageReqs.push(downloadRepos(headerLinkNext));
} else {
repoPageReqs[0].resolve(); // <-- resolve sketchiness
}
}
function downloadRepos(path) {
return $.get(path, receivedReposPage);
}
function downloadAllRepos(path) {
repoPageReqs.push(downloadRepos(path));
return $.when.apply(null, repoPageReqs);
}
$(function () {
downloadAllRepos("https://api.github.com/my/repos/path")
.then(function () {
console.log("finished downloading all repos");
})
});
The reason I use the sketchy [$.Deferred()]
was because the $.when
would resolve before the callback pushed the new $.get
promise into the promisey array.
Is there a better way to make/resolve this kind of "unraveling" chain?