Skip to content

Instantly share code, notes, and snippets.

@JasonBBelcher
Last active July 21, 2019 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JasonBBelcher/a8b62fc39582682f3ecf75ad1b07e06c to your computer and use it in GitHub Desktop.
Save JasonBBelcher/a8b62fc39582682f3ecf75ad1b07e06c to your computer and use it in GitHub Desktop.
Async currying factory to get all paginated results
// Async, curried, recursive factory to get all paginated results
function searchAndGetPaginated(baseUrl) {
return function(resource, searchQuery) {
return new Promise((resolve, reject) => {
search(`${baseUrl}/${resource}/${searchQuery ? searchQuery : ""}`);
const allPages = [];
function search(url) {
fetch(url)
.then(res => res.json())
.then(data => {
if (Array.isArray(data.results)) {
data.results.forEach(object => {
allPages.push(object);
});
getAllPages(data);
}
})
.catch(reject);
function getAllPages(data) {
if (data.next) {
search(data.next);
} else if (!data.next) {
resolve(allPages);
} else {
reject("error fetching results");
}
}
}
});
};
}
const swapi = searchAndGetPaginated(`http://swapi.co/api`);
swapi("people").then(results => {
const females = results.filter(obj => obj.gender === "female");
const regex = new RegExp("Leia" + ".*");
const Leia = females.filter(female => female.name.match(regex));
console.log(Leia);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment