AngularJS Chained Promises are limited to a single execution

Having an issue with a function that retrieves data based on user checkbox selections. When the user selects "All", the function uses chained promises to fetch the selected data according to the checkbox IDs. The first time it works perfectly, but when the user deselects and reselects "All", the promises do not chain properly. It seems like the original promises are not cleared or something similar.

This function is triggered when the user clicks the "Select All" button:

$scope.selectAll = function () {
    $scope.print.sections = angular.copy($scope.sections);
};

When the user clicks "Print Selected", this function is called:

$scope.printSections = function () {
  var promise = null;
  $scope.print.sections.sort(setOrder);
  $scope.dataLoading = true;

  var cntr = 0;
  var sections = $scope.print.sections;
  
  function next() {
      if (cntr < sections.length) {
          promise = getSectionData(sections[cntr++]);
          promise.then(next);
      }
  }
  next();
};

The function "getSectionData" retrieves data for each section based on its ID. Here is a snippet of the code:

function getSectionData(section) {
    var deferred;
    deferred = $q.defer();
    var id = section.QuestionSectionID;
    
    switch (id) {
        case 1:
            deferred.resolve(myService.getfirstSection(id)
            .success(function (data) {
                $scope.firstSection = data;
            }));
        break;
        
        case 2:
            deferred.resolve(myService.getSecondSection(id)
            .success(function (data) {
                $scope.secondSection= data;
            }));
        break;
    }
    
    return deferred.promise;
}

The issue occurs when trying to chain the promises the second time around in the "next()" function. Any help would be appreciated!

Answer №1

Here is a modified version of the code snippet provided, where I have removed the $q wrapper from the Promise. The main improvement I made was adding a default option in the switch statement to return a blank promise when a case doesn't match.

let counter = 0;
const sections = [1, 2, 989878, 3]; // Data for 989878 does not exist

function nextSection() {
  if (counter < sections.length) {
    let promise = getSectionData(sections[counter++]);
    promise.then(nextSection);
  }
}
nextSection();

function getSectionData(id) {
  let deferred = null;
  
  switch (id) {
    case 1:
      deferred = Promise.resolve(getOtherData(id).success(function(data) {
        $('pre').append(JSON.stringify(data[0], {}, ' '));
      }));
      break;
    case 2:
      deferred = Promise.resolve(getOtherData(id).success(function(data) {
        $('pre').append(JSON.stringify(data[0], {}, ' '));
      }));
      break;
    case 3:
      deferred = Promise.resolve(getOtherData(id).success(function(data) {
        $('pre').append(JSON.stringify(data[0], {}, ' '));
      });
      break;
    default: // Return a default promise object. Comment out the default case and observe the result.
      deferred = Promise.resolve(true);
      break;
  }
  
  return deferred;
}

function getOtherData(id) {
  return $.ajax({
    url: 'https://jsonplaceholder.typicode.com/users?id=' + id,
    method: 'GET'
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>
  
</pre>

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

The script is showcasing text on both instances

I am currently working on a script to show text to users who are using adblock. The script I am using is as follows: ads.js <script>var canRunAds = true;</script> index.php <script data-rocketsrc="ads.js" type="text/rocketscript">< ...

ERROR: No compatible version of jQuery Foundation could be located

Encountering issues while installing Foundation due to conflicts with Jquery. λ bower install foundation bower foundation#x cached https://github.com/zurb/bower-foundation.git#5.5.1 bower foundation#x validate 5.5.1 against https: ...

A guide on transferring values from three separate arrays into a designated div using JavaScript

Imagine having 3 div elements and 3 different sets of arrays. The goal is to assign the values from each array into corresponding divs. How can this be achieved? Take a look at my sample divs below: <div id='001'><div id="nr001">< ...

What is the method employed by Node.js to manage relative paths?

I am facing an issue with how Node.js handles paths. Despite checking the documentation, I couldn't find the solution to my problem. Basically, I have a file that contains a relative path pointing to another file (specifically a PNG image). Dependin ...

accessing various tiers of data through an application programming interface

Currently, I have successfully accessed 5 followers of a GitHub user via AJAX. I am now attempting to delve three levels deep into each of the initial 5 followers, retrieving 5 more followers at each level. Essentially, the goal is to return 5 followers, t ...

What is the best way to assign an ngModel dynamically using a dot-separated path?

I have noticed a few questions that are similar to this one, but my question has a slight variation. In my controller, I have an object that resembles the following: $scope.data = { foo: {bar: 1, bas: 2}, biz: 3, blat: 4 }; My goal is to c ...

Assistance with Troubleshooting a Complicated JavaScript/TypeScript Software

As someone new to the world of Javascript and Typescript, I am looking to gain a deeper understanding of how a specific large application runs through its steps. Can anyone suggest a debugger or other helpful tool for this task? ...

Managing data retrieval in React using the OpenWeather API

I'm currently working on a React app as part of my learning journey. I'm facing an issue with rendering the data object correctly in my component. I tried using day.key to access the information I need to display, but it's not working as exp ...

Is it possible to display a Processing message at the beginning of a datatables table already containing data?

Within my Laravel 5.7 application, I have implemented the "yajra/laravel-datatables-oracle": "~8.0" library and found a helpful thread on customizing the processing message at this link. I adjusted the processing message styling as follows: .dataTables_pr ...

Tips for creating a TypeScript function that only needs one property from an object

Looking to overcome the habit of using any in TypeScript, specifically when creating a function that adds or removes an item from an array. The key requirement is that the item must have an id property of type string. Here's how I currently have it im ...

What's the reason popstate does not trigger in Safari during the loading of an iframe?

When using Safari, I've noticed that if an iframe is loading and the user changes the history state by navigating back or forward, the popstate event doesn't get triggered. This results in the application state being out of sync with the window l ...

difficulty encountered when passing session variable on PHP pages

In my project, I have two important PHP pages: quizaction.php and result.php. The functionality involves passing variables from quizaction.php to result.php. Below is an overview of my code: <?php include 'db.php'; session_start( ...

Separate the React code from the application's codebase

Transitioning from jQuery to React, I am seeking guidance on configuring webpack to separate my code from the core React functionality. I am developing widgets with React, where each widget functions as its own "app" and can be integrated into non-React ...

Unveiling the Magic: Enhancing Raphaeljs with Interactive Click Events on a Delicious Slice of the

I'm having trouble responding to a click event on each slice of a Raphael Pie Chart. I've tried implementing the code below, but it doesn't seem to be working. The code is just two lines, commented as "My Code", in the example from the offic ...

Adding Angular dependencies through Gulp (with the help of Browserify)

Exploring the use of Gulp and Browserify in my new Angular application. Inquiry: How can I effectively include angular dependencies in the app.js file without encountering dependency errors? Even with minimal dependencies, such as using only $stateProvid ...

Using an xmlhttprequest to retrieve a PDF file functions properly in synchronous mode, but encounters issues in

Today I'm experimenting with some code that scrapes PDFs from a chrome extension by detecting user-clicked links. I've noticed that synchronous xmlhttprequests work perfectly for both HTML documents and PDFs. However, I seem to be facing an issue ...

Tracking the movement of a handheld device through GPS technology

I am interested in creating a mobile application that can track the real-time location of users who have the app installed on their devices. The concept is to allow one or more users to follow the movement of another user using GPS on a map. I plan to deve ...

obtaining the controller output in JavaScript

Scenario: Retrieving id in javascript following an ajax post I'm trying to figure out how to access the id sent from my controller's ActionResult in javascript. I've experimented with both Content Result and JSON Result on the controller, b ...

Execute the JS function during the first instance of window scrolling

Currently, I have implemented a typewriter effect on my website that triggers when the user scrolls to a specific section. However, I want this effect to occur only once. Unfortunately, every time the user scrolls again (in any direction), the function is ...

Creating a Union Type from a JavaScript Map in Typescript

I am struggling to create a union type based on the keys of a Map. Below is a simple example illustrating what I am attempting to achieve: const myMap = new Map ([ ['one', <IconOne/>], ['two', <IconTwo/>], ['three ...