I would like to fetch data from this API: "https://swapi.co/api/planets". The data is paginated like https://swapi.co/api/planets/?page=1, https://swapi.co/api/planets/?page=2....
I want to build an API which accepts url, page, and callback as arguments. It will fetch all of the data page by page, until it reaches the page specified in the arguments.
E.g.
function loadData(https://swapi.co/api/planets, 5, cb)
this will load data from page1, page2, page3, page4 and page5.
Here is my attempt however it doesn't work. Can someone please point me in the right direction ?
function fn(url, page, pages, cb) {
return new Promise((resolve, reject) => {
const endpoint = `${url}/?page=${page}`;
fetch(endpoint).then(response => {
if (response.status !== 200) {
throw `${response.status} ${response.statusText}`;
}
response.json().then(data => {
cb(data);
if (page <= pages) {
fn(url, page + 1, pages, cb)
.then(resolve)
.catch(reject);
} else {
resolve();
}
});
});
});
}
function cb(data) {
console.log(data)
}
fn('https://swapi.co/api/planets', 1, 3, cb).then(() => {});
Follow up question: if instead of passing in a callback as the argument, I want to pass in an array to collect the data loaded, how should I tweak this API?