Dealing with Asynchronous JavaScript code in a while loop: Tips and techniques

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();

Answer №1

Make sure to invoke the function only after receiving a response. Take a look at this sample:

let flag = 0;

function fetchData(nextPageToken) {

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

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

    if (nextPageToken == null) {
      flag = 1;
    } else {
      flag = 0;
      fetchData(nextPageToken);
    }
  });
}

let initialToken; // Define this appropriately

fetchData(initialToken);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are effective ways to eliminate script tags from a webpage?

I have implemented tags on my website that users can use to interact with the site. My goal is to figure out how to make the browser only read text from a specific file I write, without any HTML. This should be restricted to certain sections of my websit ...

What steps do I need to take to ensure that Phaser implements modifications made in my game.js file?

I recently completed the Phaser Tutorial and set up my project with an index.html file and a game.js file, along with downloading the phaser.min.js file. All files are located in the same folder. Although I have connected everything correctly and the outp ...

How can I enable a button in a React application when the text input is not populating

For my Instagram MERN project, I have implemented a Comment box feature for users. The Post button starts off disabled and becomes enabled when text is entered. However, despite entering text, the button remains disabled, preventing submission. Below is th ...

What could be causing the 405 error in my post request?

While attempting to send a post request to Firebase through my Vue app, I keep encountering an error illustrated in this image. I have a webpack server running and the website is on localhost:8080. However, I also have a live version hosted on hostinger a ...

Testing Your Angular 7 Code: Unit Testing Made Easy

I am currently working on developing unit tests for this angular script: export class DataService { private csrfToken: string = ''; private isContentShown: BehaviorSubject<boolean> = new BehaviorSubject(true); constructor(private h ...

Is there a method in TypeScript to make an enum more dynamic by parameterizing it?

I've defined this enum in our codebase. enum EventDesc { EVENT1 = 'event 1', EVENT2 = 'event 2', EVENT3 = 'event 3' } The backend has EVENT1, EVENT2, EVENT3 as event types. On the UI, we display event 1, event 2, a ...

react-leaflet LayerSelection creates redundant entries in table

Here is the React version I am using: 16.0.0 And for react-leaflet: 1.6.6 I recently attempted to implement a layer controller on my map which consists of two layers, each containing multiple markers. Below is an example of what I have been working on. i ...

Tips for refreshing the tawk.to widget when the language changes with the help of i18next

Utilizing i18n-jquery for language switching and integrating the tawk.to chat widget, I've successfully loaded different languages on page reload. However, due to i18n not refreshing the page (which I don't want to do), I need to figure out how t ...

When executing tests in jest, imports from node_modules may become undefined

My jest configuration seems to be encountering an issue with resolving node_modules during execution. They are coming back as undefined... Here is a snippet from my test file: import lodash from 'lodash' it('test', () => { expect ...

Generate a fresh collection of objects all sharing a common identifier within a given array

Looking for help transforming this schedules array to match the desired output. Any ideas? let schedules = [ {day: 'Sunday', time: '5:00 PM'}, {day: 'Monday', time: '4:00 PM'}, {day: 'Monday', time: &ap ...

How many intricate objects are instantiated in memory when running the code snippet provided above?

When looking at the given code, how many complex objects can we identify in memory? function Foo() { this.one = function() { return "one"; } } var f = new Foo(); Foo.two = function() { return "two"; }; Here's what I see: The Foo co ...

to streamline the process of navigating Google Chrome web pages

Is it possible to create automation in Google Chrome that can complete the following tasks: 1. Input a job name to monitor 2. Periodically click a refresh button on the webpage (not the refresh button for the entire Chrome page in the left corner) 3. Open ...

Difficulty triggering an event within a collection in Backbone.js

Having recently delved into JavaScript and Backbone, I encountered a puzzling error. Router = Backbone.Router.extend({ routes: { ":albumID": "load" }, load: function (albumID) { if (controller.collectionInitialized == true) ...

Tips for keeping a Bootstrap Modal in a fixed position on the screen as you scroll

I am facing an issue with a button that is supposed to trigger a Bootstrap Modal. It seems that the modal is not visible when the page has been scrolled down. Upon clicking the button to show the modal, the background darkens as expected, but the modal its ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

unable to transform this string into an object

https://i.sstatic.net/O46IL.pngWhy am I encountering difficulties converting this string into an object? Any assistance on resolving this error would be greatly appreciated. onSignup(data:any){ localStorage.setItem('users',JSON.string ...

I am unfamiliar with this scenario but I can utilize Axios, async/await, and TypeScript to navigate it

Having trouble creating a workflows list from an axios response Error: Argument of type 'Promise<unknown>' is not assignable to parameter of type 'SetStateAction<WorkflowForReactFlowProps[] | null>'. Here's the Axios c ...

In what way does s% access the title attribute within the Helmet component?

I am seeking clarification on how the reference to %s is connected to the title attribute of the <SEO /> component within the <Helmet /> component in the gatsby starter theme. Can you explain this? Link to GitHub repo On Line 19 of the code: ...

Using JavaScript to parse an XML document on a WAMP server

I am a beginner in the field of web development and currently struggling with parsing an XML document using JavaScript on WAMP server. I know that both the web page and XML file need to be on the same server for it to work. I tried placing both the PHP and ...

Refine keys dynamically according to the given input

I'm facing a challenge with an array wherein I need to filter out keys based on an input string. The only constant key is OLD_VAL, while the others are dynamic. Even though I attempted using a variable, it doesn't retrieve that specific key. let ...