Reputation: 358
I'm querying a REST api which includes pagination. After an initial query which gets total count and max per page, I'm trying to loop through total pages to get all of the items.
const instance = axios.create({
baseURL: 'https://api.com',
headers: {'X-Application-Key': 'APPLICATION_KEY'}
});
instance.get('/trips')
.then((response) => {
const totalTrips = response.data.count;
const totalPages = Math.ceil(totalTrips / response.data.max_per_page);
let i;
for (i = 0; i < (totalPages + 1); i++) {
instance.get(`/trips?page=${i}`);
console.log(response.data.results)
};
})
.catch(function (error) {
console.log(error);
})
This isn't working since the 'response' argument is still referencing the initial query, but it's my understanding that all .then blocks should be on the same level and not actually nested, so I'm not sure how to actually loop through the pages. What is the proper way to accomplish this?
Upvotes: 1
Views: 2543
Reputation: 1234
Here is a slightly opinionated response, using async await to handle the multiple asynchronous requests. And I think you'll want to use a function like promise.all, which allows you to make all the requests at the same time, and handle the response when all the http requests have completed.
const instance = axios.create({
baseURL: 'https://api.com',
headers: {
'X-Application-Key': 'APPLICATION_KEY'
}
});
getAlltrips();
async function getAlltrips() {
try {
const response = await instance.get('/trips');
const totalTrips = response.data.count;
const totalPages = Math.ceil(totalTrips / response.data.max_per_page);
const promiseArray = [];
for (let i = 0; i < (totalPages + 1); i++) {
promiseArray.push(instance.get(`/trips?page=${i}`));
};
// promise.all allows you to make multiple axios requests at the same time.
// It returns an array of the results of all your axios requests
let resolvedPromises = await Promise.all(promiseArray)
for (let i = 0; i < resolvedPromises.length; i++) {
// This will give you access to the output of each API call
console.log(resolvedPromises[i])
}
} catch (err) {
console.log('Something went wrong.');
}
}
Upvotes: 4