Thursday, 17 September 2020

How to consume paginated API

I don't know if this is a dumb question or not? I had a test recently and I was supposed to write a function which consumed paginated API, and I had to query on that and return the result in the same order of pages. So for example the URL is xyz.com/posts/[page] And number of pages were written in the api result only So what I did, I called it once and queried it,saved the total pages and saved the results of the first page in a results array and then called the other pages by saving them in a promises array and then I used Promise.all(PromiseArray) and then updated results when those promises got resolved by using .then and at the last I used a final .then to return the results array. Now in the APIs we generally return the response but this was a function so I had to return it and then there was a main function which was calling this function and saving the results in a variable and then outputting it. my results were correct but I wasn't able to return the responses and I couldn't just directly go at the bottom and type return results because the synchronous code would have ran first and submitted an empty array. So in my case I was only returning it in that final .then so that it returns only when the api calls are done and the result is queried. And it still gave undefined. I tried it on my local it was working.So my question is, Is it the right way to consume paginated API and query them or I wasn't returning them correctly or it was bug from their side.

Submitted September 17, 2020 at 08:28PM by cr3ax

No comments:

Post a Comment