Handling multiple promises in AngularJS is a common challenge that developers face

I am currently in the process of developing an AngularJS controller that needs to work with multiple promises, each returning a boolean value. The aim is to determine a final boolean value based on these individual results. If all returned values are true, then the result will be true. However, if even one promise returns false, the overall result will be false. Currently, I have chained all my service/DAO calls together, which causes issues when one promise is rejected. I believe there must be a better way to handle this situation.

Snippet of Controller Code:

app.controller('PromiseController', ['$scope', 'FirstService', 'SecondService', 'ThirdService', 
    'FourthService', function ($scope, FirstService, SecondService, ThirdService, FourthService) {

    var vm = this;

    vm.statusResult = false;
    vm.statusSecond = null;
    vm.statusThird = null;
    vm.statusFourth = null;
    vm.statusFirst = null;

    SecondService.getStatus()       
    .then(function(returnData){
        vm.statusSecond = returnData;
    })
    // other service calls follow...

    // logic for determining final status

    });

    return this;

}]);

Hence, I am seeking a more efficient approach to deal with multiple promises and resolve the collective outcome of all promises. Moreover, it is essential that the application remains responsive while handling these results.


UPDATE

The solution using $q.all provided by @str works well for the final result. However, I also require the individual outcomes of each service. How can I manage both the individual values and the final result simultaneously?

Answer №1

If you're looking to synchronize multiple promises, $q.all is a great solution:

var allPromises = [
    FirstService.getStatus(),
    SecondService.getStatus(),
    ThirdService.getStatus(),
    FourthService.getStatus(),
];

$q.all(allPromises)
    .then(function (results) {
        vm.results = results; // The first promise result can be accessed using vm.results[0]
        vm.status = results.every(function (result) {
            return result;
        });
    })
    .catch(function() {
        vm.status = false;
    });

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

Automatically navigate to a specific selection within the Autocomplete feature

Imagine having a dropdown or Autocomplete list in Material-UI with a long list of items. How can you make the list automatically scroll to a specific item when you open the dropdown? For instance, if we take the list of top100Films, the initial displayed i ...

Struggling to retrieve JSON data from within an array

[ { "May": [ { "year": 1994, "date": "2" }, { "Sequence": 2, "Type": "Images" } ], "_id": "1122" } ] The issue I am facing is retrieving the id except for the "date" f ...

The phase does not appear to reset back to null

In my current project, we are working on a large-scale Angular application integrated with Ruby PageObject for testing. One issue we have encountered is that occasionally an $interval triggers the $digest cycle unexpectedly, resulting in unpredictable fail ...

When transitioning to SSL, AngularJS GET requests may be disrupted and cancelled

After implementing SSL on my server, I noticed that my services, which fetch data from the backend via the REST API, are no longer functioning properly. When attempting to make requests, Chrome's network inspector shows that the requests are being "c ...

What's the best way to navigate to a different page using a function in React JS?

Hello there! I'm just starting out with React js and I've been trying to figure out how to navigate to the home page once a user successfully logs in using React. Below is the function I currently have set up, which allows me to redirect to the h ...

Discover the identities of elements that possess a specific attribute and class

I am looking to identify the ids of elements that have both the attribute data-test and the class myClass. In this scenario, the only element that meets both criteria is elem3: <input type="text" data-test="someValue" id="elem1" /> <input type=" ...

PHP AJAX request failing to access current $_COOKIE['x']

I have encountered this issue before and was able to resolve it, but this time I am seeking additional assistance. Here is the specific scenario I observed while debugging: [home page load] Session::Load() $session_uid = (new) d149f... $row = false [log ...

What is the method for mocking a function that returns an HTTP response?

My current project involves working with ExpressJS and I'm facing a challenge in stubbing a function that returns an HTTP response within a router. Specifically, I need to mock a request to Amazon S3. app.get('/', (req, res, next) => { ...

Update the display immediately upon a change in the state

In my app.js file, the code looks like this: export const App = () => { const [selectedMeals, setSelectedMeals] = useState<string[]>(["allItems"]); const onCheckHandler = (e: any) => { const checkedValue = e.target.value; if (e.targ ...

Any tips for filtering an array within an array of objects using the filter method?

I have an array of products and models that I am currently filtering based on 'id' and 'category'. var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.products = [{ 'id': 1, ...

Executing AJAX POST request with callback function

I successfully used this code for the get function to retrieve data. It works flawlessly and I am able to fetch the required data using this function. function getdata(getdatafrom, resultclass){ $.get(getdatafrom, function(data) { $(result ...

Highlight and trim lengthy text using React

Imagine I have a lengthy text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con ...

What is the reason behind my pledge giving back an array containing either [object] or [array]?

As I attempt to iterate through a list of URLs from Github's API to retrieve an array containing all the relevant information, I am encountering an issue. Instead of actual data, the array returned to me is in the format of [object],[object]. I suspec ...

Loading HTML div content on demand using AngularJS

I have been working on a project where I retrieve data from the server to update the data model on the client browser using one-way data binding. The structure of the data model is outlined below. In relation to this data model, I am displaying the conten ...

Accessing information from JSON files using AJAX

I'm currently working on loading data from a JSON file using AJAX. The file I'm referencing is external-file.json. Within the code snippet provided, there are other unrelated sections. I'm encountering an issue within the getViaAjax function ...

What is the best way to showcase JSON data on a webpage?

Currently, I have a total of 3 different objects containing education details in my JSON data. While I am able to display them in the console using a for loop, I am only able to show one object in my HTML output. How can I push all three details to my HTML ...

Create a matrix by utilizing the x and y axes to form a multi-dimensional array

var axis_x = document.getElementById("x_axis").value; // 3 var axis_y = document.getElementById("y_axis").value; // 2 for (var i=1; i <= axis_x; i++){ axs_x.push(i); // [1,2,3] alert(axs_x); } for(var j=1 ; j <= axis_y; j++){ axs_y.push( ...

Discovering a value that aligns with one of the values in an array using Javascript

Just a heads up: this quiz is super simple and only has one input field for each question. This block of Javascript code is used to check if the answer entered in the input field is correct or not. In this case, it checks if the answer entered is 'en ...

Polymer form failing to submit via AJAX in Firefox

My Form: <form is="iron-form" action="{{url('/user/store')}}" id="registerForm" method="POST"> <input type="hidden" name="_token" value="{{csrf_token()}}"> <paper-input name="email" label="E-mail" type="email"></pape ...

How to arrange data in angular/typescript in either ascending or descending order based on object key

Hey there! I'm fairly new to Angular and have been working on developing a COVID-19 app using Angular. This app consists of two main components - the State component and the District component. The State component displays a table listing all states, ...