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

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...

Error in Node.js Socket.io: The disconnect event is being triggered before the connect event

When the client reconnects after a network drop, the disconnect event is triggered on the server. Client code: var url ='192.168.1.101', port = '80', socket = io.connect('http://' + url + ':' + port, { &apo ...

Implementing jQuery slideDown effect on a nested table element

I am facing an issue where the nested table does not slide down from the top as intended when a user clicks the "Show" button. Despite setting the animation duration to 500ms with jQuery's slideDown() function, the table instantly appears. I am using ...

Acquiring the specific checkbox value using JQuery

I am encountering an issue with my JQuery function that is supposed to print out the unique value assigned to each checkbox when clicked. Instead of displaying the correct values, it only prints out '1'. Each checkbox is assigned an item.id based ...

Issue with HTML5 Canvas y-axis dimensions

I am attempting to create a basic animated HTML canvas with a moving block controlled by WASD keys. I encountered an issue where drawing a 5x5 rectangle appeared to be 5x10 on the canvas. Upon inspecting my code and logging the position of the element, I d ...

Transforming localhost into a server name in a Node.js environment

Recently I began working on full stack development. I have a physical server and I want to upload my code to it so I can run the NodeJS server from there. This way, when people try to access my site, they will use or instead of localhost:port, which on ...

I'm curious about integrating Font Awesome into my React.js project - any tips on

I'm having trouble getting Font Awesome to display in my React JS project. Here is the code I am using: import React, {Component} from 'react' import './category.css' import axios from 'axios' import Course from './c ...

Displaying Photo on Webpage using Bearer Authorization Token in JavaScript

In my JavaScript code, I am currently loading an image using the following method: var img = new Image(); img.onload = function () { .. }; img.src = src; However, I have recently realized that I need to secure the images on my server side with OAuth 2, j ...

Transforming an Angular 11 HTML template into Angular code

After attempting to transfer the Porto Admin HTML template to Angular, I encountered some issues. When including the CSS and JS dependencies in the project, everything worked fine with all the HTML code in index.html. However, when I moved the code to app. ...

How to access a file stored within a proxy object using Vue.js

I am currently working on sending a file from a vue-page to the server. To achieve this, I have implemented the following: FileFrom component: <template> <div class="FileForm" v-bind:name="name"> <label clas ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Changing the InnerHTML of a tag in JavaScript using class and id attributes

When it comes to handling these links <div class="post_actions"> <a class="color-transition article_delete" href=""><i class="fa fa-pencil"></i></a> <a class="color-transition article_edit" href="#" id="1">< ...

The process of querying two MySQL tables simultaneously in a Node.js environment using Express

My goal is to display both the article and comments when a user clicks on a post. However, I've encountered an issue where only the post loads without the accompanying comments. Here is the code snippet that I've been working with: router.get(&a ...

Challenges arising with the express search feature

Currently, I am in the process of developing an API for a to-do application. I have successfully implemented the four basic functions required, but I am facing some challenges with integrating a search function. Initially, the search function worked as exp ...

Querying JSON Data with PHP API

I have been working on creating a query.php file along with a query_result.php page to handle an API JSON feed. My issue is that even when I specify a specific "year" in the query, such as YearBuilt = "1999", the results still include vessels from all year ...

Troubleshooting problems with callback functionality in conjunction with Expressjs, JWT authentication, and Angular

For my current project, I am implementing authentication using JWT with Expressjs and Angularjs. However, I now need to integrate node-dbox to access Dropbox files of my users. The issue arises when trying to store the token received from Dropbox for user ...

Transform the selected component in Material-UI from being a function to a class

Hello, I am currently learning about React and I have started using the select button from material-ui. The code I found on the material ui page is for a functional component, but I am more comfortable with class components. Here is the code snippet provid ...

Is there a way to obtain the coordinates of an SVG element by simply clicking on a specific point?

I'm still learning about SVG and I'm trying to trigger an event that captures the click coordinates when clicking on the SVG. I have a few questions: Since I'm using Angular, I'm unsure if it's possible to keep my function in th ...

Is it possible to add a jQuery-generated element to pure vanilla JavaScript?

I am facing a challenge in creating a new notification div when an event is triggered. Ideally, I would normally achieve this using jQuery by utilizing something like $("myDiv").append(newDiv). However, in this case, the item selector to which the new div ...

Dynamically loading an iFrame source and automatically populating input forms using Javascript explained

My current challenge involves retrieving URL parameters successfully and using them to decide which iframe src to populate. Additionally, I need to autofill the form created via the form src with other parameters. However, I am faced with two main issues. ...