Looping through Angular HTTP GET requests with a new URL in the response

Utilizing the REST API of SharePoint 2010, I am retrieving data from a list that has a maximum item limit of 1000. If a list contains more than 1000 items, the response will include a key named d.__next which provides the URL for fetching the next set of results. An example URL format is:

https://{SiteURL}}/_vti_bin/listdata.svc/{listName}/?$skiptoken=1000

Initially, I assumed there would be fewer than 3000 items in the list, so I nested requests multiple times as shown in this code snippet:

    $http({
    method: 'GET',
    url: jsonLocation,
    headers: {
        "Accept": "application/json;odata=verbose"
    }
}).then(function successCallback(
        response) {
          $scope.ListData = response.data.d.results;

      if (typeof(response.data.d.__next) != "undefined") {
            $http({
                method: 'GET',
                url: response.data.d.__next,
                headers: {
                    "Accept": "application/json;odata=verbose"
                }
            }).then(function successCallback(
                response) {
               $scope.ListData.concat(response.data.d.results);
            }, function errorCallback(response) {
                console.log("HTTP Get Failed");
            });
        } else {
            executeFunction($scope.ListData)
        }

    },
    function errorCallback(response) {
        console.log("HTTP Get Failed");
    });

However, I now need to fetch data from a list with over 40,000 items, and the current approach is no longer practical.

The challenge lies in finding a way to loop through the requests while utilizing $http's asynchronous callbacks and checking for the existence of d.__next within the response data during the success callback.

What would be the most effective strategy to address this issue?

Answer №1

Here is a suggestion on how to improve your code:

$scope.ListData = [];
$scope.getData = function (url) {

    $http({
        method: 'GET',
        url: url,
        headers: {
            "Accept": "application/json;odata=verbose"
        }
    }).then(function successCallback(response) {

        $scope.ListData = $scope.ListData.concat(response.data.d.results);

        if(typeof(response.data.d.__next) !== "undefined") {

            $scope.getData(response.data.d.__next);

        } else {
            executeFunction($scope.ListData);
        }

    }, function errorCallback(response) {
        console.log("HTTP Get Failed");
    });

}

This modification involves encapsulating the existing code within a function that takes a URL parameter. It also makes use of recursion for calling the next URL when available.

Answer №2

Utilizing a concept known as Recursion, this technique involves a method continuously calling itself until it reaches a final outcome.

function fetchData(jsonURL) {
  $http({
      method: 'GET',
      url: jsonURL,
      headers: {
          "Accept": "application/json;odata=verbose"
      }
  }).then(function successCallback(
          response) {
          // console.log(response.data.d)
          $scope.DataList.concat(response.data.d.results);
          if (typeof(response.data.d.__next) != "undefined") {
              fetchData(response.data.d.__next);
          } else {
              performAction($scope.DataList)
          }

      },
      function errorCallback(response) {
          /* */
          console.log("HTTP Get Failed");
      }
  );
}

$scope.DataList = {}; // consider changing this to [] based on the data structure
fetchData(jsonURL);

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

Creating a password with two distinct numbers using regular expressions

In javascript I am struggling to create a password that meets the criteria of having at least eight characters, including two SEPARATE digits, one uppercase and one lowercase letter, as well as one special character (-, @, #, $, &, *, +) but not /, !, ? ...

What strategies can be implemented to maximize memory and CPU efficiency in NodeJS and Express?

My Node app, running on Express, utilizes a web scraping tool to gather and analyze data. While NodeJS is praised for its scalability and ability to handle numerous concurrent connections, I've noticed some difficulties when operating a web scraper t ...

Is there a way to toggle the opening and closing of a q-popup by simply clicking on the q-date element

Within the following code snippet, there is a date present. Is it possible to exclusively extract the year from q-date? I am aiming to automatically close the div when the model or container reaches a length of 4, which I have already achieved. However, up ...

Ways to obtain a full number with a leading zero

I have a number that looks like this: 0065921922572 I am passing this value as a parameter to a JavaScript function. When I alert the data, it displays like this: 65921922572 (the leading zeros are removed) I have attempted to convert the number to a ...

Unable to complete the task of executing com.github.eirslett:frontend-maven-plugin:1.6:install-node-and-npm (install node and npm)

I'm encountering an issue with Maven that's been causing some trouble: [ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.6:install-node-and-npm (install node and npm) on project xxx-frontend: Could not download Node.js: ...

The AngularJS module 'app.module' cannot be found or is not accessible

Having trouble with a FrontApp that is giving me an error related to dependencies: Uncaught Error: [$injector:modulerr] Failed to instantiate module moduleApp due to: Error: [$injector:modulerr] Failed to instantiate module app.module due to: Error: [$ ...

What is the most effective way to load data prior to the controller being loaded

Is there a way to fetch data from a service before the view and controller are loaded? I need assistance with this. resolve: { getAlbum: function(albumService){ return albumService.getAlbums(); },getAtum: function(albu ...

Having trouble injecting services into Angular unit tests, resulting in test failures

This is my custom karma configuration file: `use strict`; var path = require('path'); var conf = require('./gulp/conf'); var _ = require('lodash'); var wiredep = require('wiredep'); var pathSrcHtml = [ path.joi ...

Issue with label visibility for hidden date input in Chrome

When setting up a date input with a placeholder, I encountered an issue. To hide the actual input field while displaying the label, I used the following code: document.querySelector("#date").onchange = (e) => { document.querySelector ...

The issue with npm run build may be caused by a compatibility issue between TypeScript and lodash

Currently using typescript version 4.5.2 and lodash version 4.17.21 Running the command npm run build will trigger tsc && react-scripts build The following errors were encountered during the build process: node_modules/@types/lodash/common/objec ...

Tips for toggling the visibility of a custom video-js component when the user is inactive

I am currently utilizing VideoJS with React and I have created a custom title bar component using the videojs-overlay feature. My goal is to make the title bar fade out when the user is inactive (not moving the mouse) and fade back in as they move the mous ...

Creating a dropdown button with three dots in a table row using jQuery

I've been working with tables and I'm trying to create a dropdown list with 3 dots in each table row. I've experimented with a few libraries and custom dropdown options, but none of them seem to be working properly. What I'm looking fo ...

Using the output of one AJAX request as the input for a follow-up AJAX request

I'm currently facing an issue with my code, which looks like this: function (){ var myVar = myFirstAjaxFunction() $.ajax({ url: myUrl + myVar .... }) } The problem I'm encountering is that my first ajax function returns a string t ...

The correct usage of && and || operators in javascript

I've developed a small web application and I'm facing an issue where I want to trigger an alert when the 'enter' key is pressed if there is an empty or space value. Currently, the alert appears not only on hitting 'enter' but ...

How can I incorporate an already existing HTML element into a modal window?

Imagine a user interface featuring a unique custom component called <foo> - for now, let's consider it as just plain text. <foo id="foo-id">SOMETEXT</foo> I want to showcase this content in two areas of the UI, one of whic ...

What to do when VueJs computed method throws an error: "Cannot access property 'words' of undefined"?

Here is some pseudo code that I've written: var vm = new Vue({ el: '#test', data: { words: [{name:'1'}, {name:'2'}, {name:'3'},{name:'4'},{name:'5'},{name:'6'}], } ...

The impact of returning a JSON object in a Javascript constructor

When it comes to using a JavaScript constructor to return a JavaScript object literal or simply setting properties with this.XYZ, are there any performance or functional differences? Consider the following example: function PersonA(fname, lname) { ...

How to iterate through a Vue data object using forEach loop

I am currently working with a variable in my data: data: function () { return { myVariable: false, } } I'm trying to figure out how to access this variable within a looping function, like the example below: anArray.forEach(functi ...

The RXJS Scan operator is sending out a lone element

I've been experimenting with the RXJS scan operator, but I'm struggling to understand it fully. My goal is to make the scan operator not return the accumulated result, but rather the emitted items from the source if bufferResults is set to false. ...

Tips for retrieving the tenth document in Firestore Query using JavaScript

Specifically, a selection of the arranged files. Here's my thought, although I know it can be improved: firestore().collection("queue").orderBy("order_id", "asc").limit(3,5) If anyone has a better solution, I would appre ...