Ron F
Ron F

Reputation: 390

How to handle async code within a loop in JavaScript?

I am reaching out to a SongKick's REST API in my ReactJS Application, using Axios.

I do not know how many requests I am going to make, because in each request there is a limit of data that I can get, so in each request I need to ask for a different page.

In order to do so, I am using a for loop, like this:

while (toContinue)
{
    axios.get(baseUrl.replace('{page}',page))
        .then(result => {
              ...
            if(result.data.resultsPage.results.artist === undefined)
                toContinue = false;
        });
    page++;
}

Now, the problem that I'm facing is that I need to know when all my requests are finished. I know about Promise.All, but in order to use it, I need to know the exact URLs I'm going to get the data from, and in my case I do not know it, until I get empty results from the request, meaning that the last request is the last one.

Of course that axios.get call is asynchronous, so I am aware that my code is not optimal and should not be written like this, but I searched for this kind of problem and could not find a proper solution.

Is there any way to know when all the async code inside a function is finished? Is there another way to get all the pages from a REST API without looping, because using my code, it will cause extra requests (because it is async) being called although I have reached empty results?

Upvotes: 1

Views: 69

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138567

Actually your code will crash the engine as the while loop will run forever as it never stops, the asynchronous requests are started but they will never finish as the thread is blocked by the loop.

To resolve that use async / await to wait for the request before continuing the loop, so actually the loop is not infinite:

async function getResults() {
 while(true) {
   const result = await axios.get(baseUrl.replace('{page}', page));
   // ...
   if(!result.data.resultsPage.results.artist)
     break;
 }
}

Upvotes: 2

Related Questions