Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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