0

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();
Jay Sinha
  • 45
  • 6

1 Answers1

0

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);
AlexH
  • 766
  • 4
  • 21
  • I added infinite while loop to get data from each page since max data per page is 50. It works for single page but how do I get all say 203 datas. – Jay Sinha Oct 20 '20 at 17:38
  • If there are 203, call it 203 times (for loop). This will run thousands of times (I think, it's a big number for sure) before it stops. An infinite loop is rarely a good idea. – AlexH Oct 20 '20 at 17:40
  • In the response object I am getting an array of 50 items. To grab the rest I have to request for next page. nextPageToken is provided in response object. That's why I was using infinite loop since tha last page has nextPageToken: null – Jay Sinha Oct 20 '20 at 17:45
  • Then you'll want to use recursion. I'll add an example – AlexH Oct 20 '20 at 17:46
  • That should work. It might need modification to fit your use, but it's a template. – AlexH Oct 20 '20 at 17:48