I need to get a list of items from an API endpoint (/products), but they are paginated (max of 200 items per page).
I need to make a loop which will get 200 products, push to an array, and increase the page number, so it can ask for more 200 products. It will stop when there's a 404 error (page does not exist), meaning that I got all the products.
I'm using Axios for the requests, which is Promise-based, but I can't get it to work. I've tried several things, even creating my own Promises, but the results are the same:
- Can't make it wait for all the pages to be requested
- It will always request the same page because the page increment is inside .then of the promise (to be sure that I won't go beyond the last page)
I know that the idea of Promises is to be async, but I'm trying to find a way to make it work.
Anyone has any idea of what logic could I use to do this? I just want to get all the items before moving on. Maybe I'm overcomplicating, some clarification would help a lot.
EDIT:
Tried making it recursively, but the result always return before the execution:
module.exports = {
sync(req, res) {
// Get all products page by page
var products = module.exports.getProductsByPage()
res.status(200).send(products)
},
getProductsByPage(page = 1, products = []) {
nuvemshop.get(`products?page=${page}&per_page=200`)
.then(res => {
console.log('GET Products PAGE ' + page)
products.push(res.data)
arguments.callee(++page, products)
})
.catch(e => {
if(e.response.status === 404) {
console.log('LAST PAGE REACHED')
return products
} else
return e
})
},