Angular does not always interpret the value returned from a Promise.all call

One of the challenges I'm facing is related to the structure of my controller:

controller.things = ['a', 'b', 'c'];
controller.loading = true;
controller.responses = [];

controller.handlePromises = function(){
   var promises = [];

   for(promiseIndex = 0; promiseIndex < controller.things.length; promiseIndex++) {
        promises.push(controller.promise(things[promiseIndex]);
    }

    Promise.all(promises).then(function success(response){
        for(responseIndex = 0; responseIndex < response.length; responseIndex++){
           responses.push(response[responseIndex].data);
        }
        controller.loading = false;
    }
}

controller.promise = function(value){
   //Some $http request to Database;
}

controller.handlePromises();

The amount of stuff in controller.things is dependent on the user. Connected to this controller is a straightforward HTML page that performs the following actions:

<div ng-if="!controller.loading">
    <div ng-repeat="response in controller.responses">
       {{response}}
    </div>
</div>

An issue I've encountered while working on this project is that there seems to be a 50/50 chance for the content to become visible. At times, even after loading is set to false and promises have been resolved, the content remains hidden. There are also instances where the ng-repeat does not recognize the values in controller.responses.

How can I ensure that the ng-if evaluates controller.loading as false only after all promises have been resolved, regardless of how long it takes? Similarly, how can I fix the problem with ng-repeat not displaying the values in controller.responses at times? I've thought about using a timeout, but it's not an ideal solution given the varying time it takes for the promises to resolve.

Answer №1

The issue lies in your usage of Promise.all instead of $q. Angular's $q is a specialized Promise library created by the Angular team that automatically handles the $digest cycle for you.

$q.all(promises).then(function success(response) {
  for (responseIndex = 0; responseIndex < response.length; responseIndex++) {
    responses.push(response[responseIndex].data);
  }
  controller.loading = false;
});

For more information on $q, click here

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

Unable to cancel $interval within factory

I created a factory for long-polling, complete with start and stop methods. However, I am struggling to cancel the timer. Any suggestions or ideas? app.controller("AuthCtrl", function($scope, $http, $window, User, Poller) { Poller.start(1, $scope.sess ...

Understanding the document.domain feature in Javascript

I have a website called foo.com hosted on server bar. Within this website, I have created a subdomain called api.foo.com. To connect the subdomain with Google Apps, I have set up a CNAME entry pointing to ghs.google.com. Now, I am facing an issue when att ...

Is there a way to target a sibling element of another element by using its identifier in Cypress?

My current task involves clicking a checkbox within a list of table rows. The only way I can think of reaching this level is by targeting the span tag along with its corresponding name. cy.get('tr > td > span').contains('newCypressTes ...

Determine the moment at which the input is altered by adjusting the slider

I'm encountering an issue with making this work. My goal is to calculate input bmi_val whenever one of the other 2 inputs is modified. These inputs can be changed either directly by the user (entering a value into one of them) or through a jQuery sli ...

The functionality of the button is affected when it is placed on the same line as a h1 heading

My goal is to have the page title and profile button aligned on the same line in the header of each page. However, I've encountered an issue where the button doesn't function properly when placed on the same line but works fine when separated ont ...

Exploring the issue of why the scroll event handler is not functioning properly within the useEffect hook

After creating a custom hook to retrieve the scroll state of an element, I noticed that the scrollHandler only triggers once. Here's my code: import { MutableRefObject, useEffect, useState } from "react" export const useScrollState = <TE ...

Calculating JS functions before images are loaded

Following up on a previous question, I am utilizing JavaScript code from another article to position a "content" div relative to a fixed div in my project. However, the issue arises when the positioning of the "content" div is calculated only after all the ...

Preventing Shift: How to Only Replace the Chosen Vue Draggable Item Without Affecting Other Grid Items

Let's try an example to demonstrate: https://codesandbox.io/s/j4vn761455?file=/src/App.vue:112-116 Step 1: Drag item 4 to where 5 is. Notice how 4 and 5 switch positions. Step 2: Now, drag item 1 to position 6. Watch as 1 moves to where 6 was, pushi ...

The Javascript setTimeout Function Prolongs Its Operation

Currently, I have a web app index page that performs two main tasks. Firstly, it geocodes the user's location and stores it in a JavaScript variable called "variableToSend." Secondly, it sends this data to mySQL using a PHP script after a delay of 10 ...

How can I perform a drag and drop action using Protractor?

Currently, I am working on a protractor test that requires dragging and dropping elements. The previous developers used angular drag and drop to implement this feature. After searching for a few hours, I haven't been able to figure out how to successf ...

This route does not allow the use of the POST method. Only the GET and HEAD methods are supported. This limitation is specific to Laravel

I am encountering an issue while attempting to submit an image via Ajax, receiving the following error message: The POST method is not supported for this route. Supported methods: GET, HEAD. Here is the Javascript code: $("form[name='submitProfi ...

Having trouble with passing the callback for nested mysql queries in Async.waterfall?

I am facing an issue with my nested MySQL queries where async.waterfall is not working as expected. The second step of the waterfall is failing to append its result to the array: async.waterfall([ function(callback) { connection.query(query, function( ...

How can I showcase the index of `<tr>` and `<td>` elements in a dynamically generated table

How can I print the index of table rows and data on click in javascript? <html> <head> <title>Table Creation</title> <script language="javascript" type="text/javascript"> function createTable() { ...

What is the reason behind the shifting behavior of e.currentTarget when using event delegation in jQuery?

Click here for the code snippet <div id="container"> <button id="foo">Foo button</button> <button id="bar">Bar button</button> </div> $('#container').on('click', function(e) { var targ ...

Issue: When calling setState(...), you must provide either an object containing the state variables to update or a function that will return an object with the updated

Encountering an error in the else section with this.state.incorrect + 1 and this.state.correct + 1 I've come across a similar issue that wasn't resolved by visiting this link: React Native: setState(...): takes an object of state variables to up ...

Is it possible to establish a scope for jquery.ajaxSetup()?

Currently, I am working on a project involving numerous ajax calls with repetitive parameters. After some consideration, I am contemplating using jquery.ajaxSetup() to streamline the code. However, jQuery does not recommend this approach in their API docu ...

The output from the NodeJS storage module function

Attempting to implement Two-Factor Authentication in my initial NodeJS project, which serves as a learning tool for Node. While the function correctly retrieves values from data_url, when I assign it to a variable and return data_url, it returns 'und ...

Is the Order of a JSON Array Dependable?

When working with JSON, it's clear that relying on the ordering of key-value pairs may not be reliable. For instance, a JSON parser could interpret { "someKey" : "someValue", "anotherKey" : "anotherValue", "evenAnotherKey" : "evenAnotherV ...

AngularJS data binding will only take place on the page after a user performs an action

Recently, I developed my first angular application that showcases data from a list using ng-repeat. The controller responsible for the view assigns various variables to scope - some directly within the function and others obtained through an API request. ...

Save the status of checkboxes in a JSON file using boolean values of true or false

When a user submits a form, I am retrieving the values of checkboxes and storing them as an array. The simplified form structure is as follows: <!-- gym_create.html - other input fields are omitted for brevity --> <form class="create-gym" role=" ...