While attempting to retrieve information from an API using $.getJSON()
, I encountered a challenge. The maximum number of results per call is limited to 50, and the API provides a nextPageToken
for accessing additional pages.
In the code snippet below, my intention is to terminate the loop when the nextPageToken
becomes null. However, it seems like setting a flag will not be effective in achieving this.
Moreover, I suspect that the while loop may not operate as expected due to the asynchronous nature of $.getJSON(), causing the value of nextPageToken
to remain null and resulting in premature loop termination.
SUMMARY: 1. I aim to collect data from each page. 2. I need guidance on how to properly exit the while loop.
let nextPageToken = null;
let flag = 0;
function getAll(){
while(true){
let params = {
part: "snippet",
key: key,
nextPageToken: nextPageToken,
maxResults: 50,
playlistId: playlistId
}
$.getJSON(URL, params, response=>{
console.log(response);
arr.push(response.nextPageToken);
nextPageToken = response.nextPageToken;
// incorrect approach
if(nextPageToken == null) {
flag = 1;
break; //This break statement is illegal
}
});
// This won't work either
if(flag==0) break;
}
}
getAll();