Reputation:
With a typical pagination API that returns
{
"data": ...,
"nextPageHref": <url>
}
how can I fetch all the pages in JavaScript without using recursion?
(the recursive solution is something like)
fetchPaginated(url) {
return fetch(url).then(result => result.nextPageHref
? fetchPaginated(result.nextPageHref).then(results => _.concat(result, results))
: result
}
Upvotes: 2
Views: 500
Reputation: 29936
AFAIK the only way to do it without recursion is a native support to async-await and use a for loop. Note that compiled async-await will compile to some disguised recursive code too.
But this recursion is not recursion, as the call to fetchPaginated
is called from a callback, so the sync call stack will always be emptied before the callback (And thus it is little to do with tail recursion). If you are concerned about the browsers async call stack (which is there for debugging purposes only, we don't need async call stack to run a program), I think there should be a checkbox somewhere in the browsers developer tools to turn it off.
Upvotes: 2
Reputation: 2739
I guess you could send the total number of pages upon asking for the page - /get_page?page_num=4
:
{
"data": ...,
"number_of_pages": 73
}
this will let you know if you can ask for page 5.
Additionally it has an advantage that you can let user skip 5 pages or access the last page, which you can't do with the approach you suggested.
Upvotes: 0