grrrrrr
grrrrrr

Reputation: 1425

How can I use Javascript fetch() to get REST paginated data without recursion?

I am working with a REST API that has paginated data and I need to be able to access all of the pages at once using Javascript in my React Native app with fetch/promise. In Python I would be able to do it like this:

new_result = requests.get(url+offset)
while len(new_result) == 1000:
    new_result = requests.get(url+offset).json()
    result += new_result
    offset += 1000

I can't seem to find an analogous solution without going recursive which I would like to avoid. Is there a way to accomplish this in Javascript? If recursion is the only way forward are there any recommended patterns?

Upvotes: 1

Views: 2972

Answers (2)

Evert
Evert

Reputation: 99687

Assuming you don't want to async/await, it's fine to 'recur' from your then() callback. It looks like recursion, but you're not actually increasing the stack with every iteration.

This is because the callback you passed to then() is indirectly called from the main event loop.

You simply can't use a straight-up loop because the process is asynchronous, unless you use co-routines (requires a browser that supports generators) or async/await.

Upvotes: 0

rpadovani
rpadovani

Reputation: 7360

If it is ok for you using async/await, you can do something like this:

let newResult = await fetch(url+offset)
while (newResult.length === 1000) {
    newResult = await requests.get(url+offset);
    result += await newResult.json();
    offset += 1000;
}

Upvotes: 2

Related Questions