Last active
July 21, 2019 19:37
-
-
Save JasonBBelcher/a8b62fc39582682f3ecf75ad1b07e06c to your computer and use it in GitHub Desktop.
Async currying factory to get all paginated results
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
// 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