AI solution for JavaScript Coding Question on BFE.dev
56. call APIs with pagination
Here's one possible solution using a regular loop:
const fetchListWithAmount = async (amount = 5) => { const result = []; let since; while (result.length < amount) { const response = await fetchList(since); const items = response.items; if (items.length === 0) { break; } result.push(...items); since = items[items.length - 1].id; } return result.slice(0, amount);};
In this function, we start with an empty result
array and a since
variable that holds the last item ID from the previous page. We use a while
loop to keep fetching pages until we have enough items in the result
array, or until we reach the end of the pagination (i.e., the server returns an empty array).
Inside the loop, we call fetchList(since)
with the since
parameter to fetch the next page of items. We append the new items to the result
array using the spread operator (...
), and update the since
variable to the ID of the last item in the new page.
At the end of the loop, we return the first amount
items from the result
array (or all of them if there are less than amount
items).
Note that we use async/await
to handle the asynchronous nature of the API calls, but the loop itself is synchronous. This means that we're not making multiple API calls in parallel, but one after the other. If you want to make them in parallel, you can use Promise.all()
to wait for all the API calls to finish, but that can put more load on the server and may not be necessary if the response time is fast enough.