The $q.all() function in angular seems to struggle with resolving properly

Having trouble with 3 $http calls in a factory.

Creating 4 promises:

var promise = $q.defer(),
  PBdeferred = $q.defer(),
  Rdeferred = $q.defer(),
  Pdeferred = $q.defer();

Making the first call to the API:

$http.get('/pendingBills').then(function(response) {
  var PendingBills = ['id', 'path', 'reservas', 'importe', 'fecha'];
  PBdeferred.resolve(PendingBills);
});

Resolving the last 2 promises with an empty array for now:

Rdeferred.resolve([]);
Pdeferred.resolve([]);

Using $q.all here:

$q.all([PBdeferred, Rdeferred, Pdeferred]).then(function (results){
    console.log('Results', results);
    promise.resolve({
      PendingBills: results[0],
      Remittances: results[1],
      Payed: results[2]
    });
  });

Returning the top-level promise:

return promise.promise;

The console log displays the promises, but I expected them to be resolved at this point.

Any ideas on how to fix this?

Answer №1

Your usage of $q.all is incorrect. It requires an array or object of promises, not deferreds.

Modify it to:

$q.all([PBdeferred.promise, Rdeferred.promise, Pdeferred.promise])

Answer №2

Your approach to promises seems to be incorrect, as using deferred can actually break the chain of promises. Instead of using deferred, it is recommended to obtain a promise for each action and then combine them using $q:

var PBpromise = $http.get('/pendingBills').then(function(response) {
  return ['id', 'path', 'reservas', 'importe', 'fecha']; // this will return a promise with the array as the resolve value
});

var Rpromise = $q.resolve(); // a promise that is resolved immediately. Later you can replace it with the $http call 

var Ppromise = $q.resolve(); // a promise that is resolved immediately. Later you can replace it with the $http call 

var promise = $q.all([PBdpromise, Rpromise, Ppromise]).then(function (results){ // $q.all also returns a promise
    console.log('Results', results);
    return { // this will be the resolve value of the returned $q promise
      PendingBills: results[0],
      Remittances: results[1],
      Payed: results[2]
    };
  });

It's worth noting that $q.resolve() is only supported in Angular 1.4 and newer versions. For older versions, you can use $q.when({}) instead of $q.resolve().

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

Clicking on the React Bootstrap Checkbox within the Nav component does not trigger a rerender of the NavItem component

Encountering an unusual issue while using a Nav and NavItem with a Checkbox from React Bootstrap. What I've noticed is that when clicking directly on the checkbox instead of the NavItem button, the checkbox does not re-render correctly even though my ...

There was an error in Angular at core.js:6150 stating that the object is not iterable due to a

I am facing an issue in displaying the First Name of a user in an HTML file getFirstName(id: any){ this.users = this.afs.collection('users', ref => ref.where("uid", "==", id)).valueChanges(); this.users.subscribe(users => { ...

How to Assign a Specific ID to the Body Tag in Wordpress Using functions.php

Struggling to find a simple solution after scouring the web for answers. Most tutorials are overly complicated. I'm attempting to integrate a jQuery menu system into my Wordpress site and want to assign a unique body ID to make targeting easier. I p ...

display the text content of the chosen option on various div elements

I created a subscription form that includes a category dropdown select field. The selected option's text value needs to appear 4 times within the form. It's all part of a single form. <select name="catid" onchange="copy()" id="catid" class="i ...

Issue with Build System CTA's/Callback function functionality not operational

I have encountered an issue with my build/design system. Although everything works fine during development, when I publish my package and try to use the callback function, it does not return the necessary data for me to proceed to the next screen. I tried ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

Navigate through modals with ease using Angular Bootstrap UI's Next/Previous feature

As a newcomer to Angular, I am using it to filter through a large list of products and display additional details in a modal when selected. I have found an example of a next/previous modal that does not utilize bootstrap UI, but I have yet to come across ...

I am looking for an image search API that supports JSONP so that users can easily search for images on my website

I am currently in the process of creating a blog platform. My goal is to allow users to input keywords on my site and search for images directly within the website. This way, I can easily retrieve the URL of the desired image. ...

Exploring the basics of utilizing React Testing Library to test a component - a beginner's dive into this innovative testing tool

I've been working on learning how to test 2 components using react-testing-library, but I've hit a roadblock. The component in question is NestedLists.js import React from 'react' export const NestedLists = ({filteredData}) => { ...

Bootstrap Tags Input - the tagsinput does not clear values when removed

I am attempting to manually remove the input value from bootstrap-tags-input when the x button is clicked, but the values are not changing in either the array or the inputs. This is the code I have tried: $('input').tagsinput({ allowDuplica ...

An error message 'module.js:557 throw err' appeared while executing npm command in the terminal

Every time I try to run npm in the terminal, I encounter this error message and it prevents me from using any npm commands. This issue is also affecting my ability to install programs that rely on nodejs. $ npm module.js:557 throw err; ^ Error: Cannot ...

Reload the MEN stack webpage without the need to reload the entire page

I am in the process of developing a data analytics dashboard using the MEN stack (MongoDB, Express.js, Node.js). I have successfully implemented functionality to display real-time data that refreshes every 5 seconds without the need to reload the entire ...

Creating Dynamic Height for Div Based on Another Element's Height Using ReactJS and CSS

I'm attempting to set a fixed height for a div in order to enable overflow scrolling. However, I am encountering issues as I am using JavaScript within a useEffect hook to accomplish this task. The problem is inconsistent as sometimes the height is se ...

An easy way to place text along the border of an input field in a React JS application using CSS

I am struggling to figure out how to create an input box with text on the border like the one shown in the image below using CSS. I have searched extensively but have not been able to find any solutions to achieve this effect. I attempted using <input&g ...

The command "actions" in Selenium is not recognized

I am having trouble trying to perform a mouse click based on position. No matter what I try, I keep receiving the same error message. I encountered this issue when attempting a double click on the main search bar of google.com. For assistance, refer to: ...

Issue occurs when trying to access the 'set' property of an undefined variable, leading to an error message stating "Cannot read property 'set' of undefined" while using 'this

I'm facing an issue while setting up basic cookies for my Vue project. When I try to set a cookie, I encounter the following error. My package.json file indicates that I am using vue-cookies version ^1.7.4. The error message occurs when I click the bu ...

Implementing dual pagination components in Vue JS for dynamic updates on click

Having two pagination components on a single page is convenient for users to navigate without scrolling too much. One component is placed at the top and the other at the bottom. The issue arises when I switch to page 2 using the top component, as the bott ...

Ensuring User Input Integrity with JavaScript Prompt Validation

I need help with validating input from a Javascript prompt() in an external js file using HTML code. I know how to call the Javascript function and write the validation logic, but I'm unsure how to handle the prompt and user input in HTML. Do I need ...

ng-options incorporating various conditions

I am facing an issue with the filter on a select element in my code. The filter is currently set to exclude the 'public' string from an array under certain conditions. However, I have realized that additional conditions need to be met in order fo ...

Use a route segment as the callback argument

I am new to working on my first express app. I am wondering if there is a way to pass a route segment as an argument to a callback? app.get('/connect/:mySegment', myCallback(mySegment)); For example, I am utilizing passport with multiple authen ...