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

Utilize AngularJS ngResource to transmit JSON data to the server and receive a response

My Angular JS application requires sending data to the server: "profile":"OLTP", "security":"rsh", "availability":"4", "performance": { "TRANSACTION_PER_SEC":1000, "RESPONSE_TIME":200, "CONCURRENT_CONNECTION_COUNT":500, "STORAGE_SIZE": ...

swap out the CSS class for my own class dynamically

When I display HTML code like this <div class="btn btn-pagination"> <i class="fa fa-angle-right"></i> </div> and want to replace fa fa-angle-right with myClass when the page loads. I attempted: $(document).ready(function () { ...

"Troubleshooting a problem with Mongoose's findOne.populate method

There is an array of user IDs stored in the currentUser.follow property. Each user has posts with a referenceId from the PostSchema. I am trying to populate each user's posts and store them in an array called userArray. However, due to a scope issue, ...

Encountering a "Error 404: Page Not Found" message when trying to request a json object from a node server

Working on a RESTful API, I have set it up to run on node.js using express.js, mongodb with mongoose for object modeling, and body-parser for passing HTTP data. However, whenever I start the server and try to access the specified IP address, I encounter a ...

In the world of Node.js, an error arises when attempting to read properties of undefined, particularly when trying to access the

I am currently attempting to integrate roomSchema into a userSchema within my code. Here is the snippet of code I am working with: router.post('/join-room', async (req, res) => { const { roomId, userId } = req.body; try { const user = ...

What is the best way to customize material components using styled components?

What is the best approach to override material components with styled components, considering that material-ui component classes typically have higher priority than styled-component classes? Is using the !important flag the most effective solution? <bu ...

Error: AngularJS has encountered an Uncaught ReferenceError stating that the controller is not defined within the

The code I am working with looks like this; var app = angular. module("myApp",[]). config(function($routeProvider, $locationProvider) { $routeProvider.when('/someplace', { templateUrl: 'somete ...

What steps can be taken to verify if the userID retrieved from req.user in Passport JS matches the userID in MongoDB before making any updates or deletions

Currently, I am developing a voting application that includes a feature for authenticated users to delete and edit their own polls using Passport JS authentication. My Passport setup with Node/Express looks like this: passport.use(new FacebookStrategy({ ...

Is it possible to use a Proxy-object instead of just an index when changing tabs in material-ui/Tabs?

Using material-ui tabs, I have a function component called OvertimesReport with Fixed Tabs and Full width tabs panel: const TabContainer = ({children, dir}) => ( <Typography component="div" dir={dir} style={{padding: 8 * 3}}> {children} & ...

Putting off the execution of a setTimeout()

I'm encountering difficulties with a piece of asynchronous JavaScript code designed to fetch values from a database using ajax. The objective is to reload a page once a list has been populated. To achieve this, I attempted to embed the following code ...

Switch classes according to scrolling levels

My webpage consists of multiple sections, each occupying the full height and width of the screen and containing an image. As visitors scroll through the page, the image in the current section comes into view while the image in the previous section disappe ...

I'm working on separating the functionality to edit and delete entries on my CRM model, but I'm having trouble finding a way to connect these buttons with my data fields

I am encountering some difficulties while trying to implement separate functionality for editing and deleting items on my CRM model. I have already created the necessary API in Angular, but I am struggling to bind these buttons with my field. Any assistanc ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

What could be causing React Router to fail in navigating to a nested route?

In my App.js file, I am implementing front-end routing using react-router-dom version 6.11.2: import "./App.css"; import { Route, RouterProvider, createBrowserRouter, createRoutesFromElements, } from "react-router-dom"; // Othe ...

Discovering if an input field is read-only or not can be achieved by using Selenium WebDriver along with Java

Currently, I am utilizing selenium webdriver along with Java to create a script. One issue we are encountering is that certain fields become disabled after clicking on a button. We need to determine if these fields are transitioning into readonly mode or ...

Icon for TypeScript absent from npm package listings

Recently, I created a package and uploaded it to the npm repository. The package was displayed with an icon labeled "ts" on the website. https://i.stack.imgur.com/LoY1x.png The accompanying package.json showcased the inclusion of the "ts" icon - https:// ...

Can a synchronous loop be executed using Promises in any way?

I have a basic loop with a function that returns a Promise. Here's what it looks like: for (let i = 0; i < categories.length; i++) { parseCategory(categories[i]).then(function() { // now move on to the next category }) } Is there ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

Do AJAX requests make Cross-site scripting attacks more significant?

Currently, I am in the process of developing a React application that utilizes a PHP (Codeigniter) backend. Despite Codeigniter not handling this issue automatically, I have taken it upon myself to delve into the matter. While I comprehend the importance ...

Exploring the implementation of useMediaQuery within a class component

Utilizing functions as components allows you to harness the power of the useMediaQuery hook from material-ui. However, there seems to be a lack of clear guidance on how to incorporate this hook within a class-based component. After conducting some researc ...