How to handle Asynchronous JavaScript code inside a while loop?

211 views Asked by At

I was trying to fetch data from an API using $.getJSON(), but I ran into a problem. Maximum results per call which I can get is 50. However nextPageToken is provided by the api to get data from another page. In the while loop (below code) I want to break the loop when nextPageToken is null but how do I do that from the callback function. I tried setting a flag but I realized that won't work too.

Also I think the the while loop will not work as expected because $.getJSON() will run asynchronously and nextPageToken will stay null and the loop will break.

SUMMARISING: 1. I want to get data from each Page. 2. I want to know how to break the while loop.

let nextPageToken = null;
let flag = 0;
function getAll(){

    while(true){
        let pyl = {
            part: "snippet",
            key: key,
            nextPageToken: nextPageToken,
            maxResults: 50,
            playlistId: playlistId
        }

        $.getJSON(URL, pyl, pd=>{
            console.log(pd);
            arr.push(pd.nextPageToken);
            nextPageToken = pd.nextPageToken;

            // this is wrong
            if(nextPageToken == null) {
               flag = 1;
               break;  //This break statement is illegal
            } 
        });
        // This won't work too
        if(flag==0) break;
    }
}

getAll();
1

There are 1 answers

5
AlexH On

You need to call the function after you have a response. Here's an example:

let flag = 0;

function getAll(nextPageToken) {

  let pyl = {
    part: "snippet",
    key: key,
    nextPageToken: nextPageToken,
    maxResults: 50,
    playlistId: playlistId
  }

  $.getJSON(URL, pyl, pd => {
    console.log(pd);
    arr.push(pd.nextPageToken);
    nextPageToken = pd.nextPageToken;

    // this is wrong
    if (nextPageToken == null) {
      flag = 1;
    } else {
      flag = 0;
      getAll(nextPageToken);
    }
  });
}

let startingToken; // Whatever this should be

getAll(startingToken);