Guide on utilizing angularjs $q.all() method with a dynamically generated set of promises

I am currently facing an issue with using $q.all() to wait for multiple promises to be resolved. I have created an array of promises and passed it to the all() method, but it doesn't seem to be working as expected. The promises in the array are generated by $resource objects within each iteration, which leads me to believe that the asynchronous filling of the promises array is causing the problem.

My observation is that the promise array returned by the $q.all() method is always empty. It appears that $q.all() does not wait for the array to be populated. However, I cannot be certain if this is indeed the root cause of the issue.

If it is not possible to achieve my goal with $q.all(), I would greatly appreciate any guidance on alternative methods to execute code once all promises have been resolved.

Below is the code snippet I am currently working with:

        var promisesArray = [];            
        var images, postObject;
        files.readFile('images.txt')
        .then(function (data) {
            images= angular.fromJson(data);                
            images.forEach(function (image, idx) {
                var deferred = $q.defer();                    
                if (!image.sent) {
                    files.readFile(image.name)
                    .then(function (data) {
                        postObject = angular.fromJson(data);
                        $resource(EndPointsService.baseURL + "images").save(postObject, function(data) {
                            deferred.resolve(data);
                            if (data.status) {                                    
                                image.sent= true;                                    
                            }
                        },function(error){
                          console.log(error);  
                        });
                        promisesArray.push(deferred.promise);
                    },function(error){
                        console.log(error);
                    });
                }
            });


              $q.all(promisesArray).then(function (data) {
                    console.log(data);
                    files.writeFile("images.txt", images)
                    .then(function (data) {                        
                        console.log(data);
                    }, function (error) {
                        console.log(error);
                    });
              });
       },function(error){
          console.log(error)
       });

Answer №1

The .then method of a promise generates a new promise based on the data it receives.

To create a promise array within the .then method, you should initialize it like this and return the resulting $q.all promise back to that same .then method:

var images, postObject;
var arrayPromise = files.readFile('images.txt')
  .then(function (data) {
    var promisesArray = [];
    images= angular.fromJson(data);                
    images.forEach(function (image, idx) {
        var deferred = $q.defer();                    
        if (!image.sent) {
            var promise = files.readFile(image.name)
              .then(function (data) {
                postObject = angular.fromJson(data);
                var url = EndPointsService.baseURL + "images"
                return $resource(url).save(postObject).$promise;
            });
            promisesArray.push(promise);
        };
    });
    return $q.all(promisesArray);
});


arrayPromise.then(function (dataArray) {
    console.log(dataArray);
    //Process data 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

How can I intercept/manage the back button of the browser in React-router?

Utilizing Material-ui's Tabs, which are controlled, I am implementing them for (React-router) Links in the following manner: <Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/> <Tab value={1} label="users ...

The ReactJS redirect URL is constantly changing, yet the component fails to load

I recently started using reactjs and I encountered an issue with routing from an external js file. Here is the code in my navigation file, top-header.js import React from 'react'; import {BrowserRouter as Router, Link} from 'react-router-do ...

Creating a seamless integration between a multi-step form in React and React Router

I've been learning how to use React + ReactRouter in order to create a multi-step form. After getting the example working from this link: , I encountered an issue. The problem with the example is that it doesn't utilize ReactRouter, causing the ...

Having trouble with your custom accordion content in React JS not sliding open?

Check out my progress so far with the fully functioning view here This is the structure of the Accordion component: const Accordion = ({ data }) => { return ( <div className={"wrapper"}> <ul className={"accordionList ...

"SyntaxError: import statements can only be at the top level of a module" is the error message that I keep encountering.`

For the complete code, click here: https://github.com/vscodr/axios_issue After spending some time away from JavaScript working in Python, I decided to come back and try to tackle similar tasks using JS. However, I seem to be stuck at a very basic issue! D ...

Ways to activate javascript following a PHP submission?

It's a bit tricky to explain. function m(val){ var element=document.getElementById('othermethod'); if(val=='others') element.style.display='block'; else element.style.display=&apo ...

Having difficulty launching a new window within an app built with Electron and Nexjs (Nextron)

Attempting to launch a (Nextjs-generated) page in a new window is causing an error message to appear: Uncaught ReferenceError: global is not defined Here is the full error: react-refresh.js?ts=1665849319975:10 Uncaught ReferenceError: global is not de ...

Retrieve the targeted row from the table and then employ a function

Here is a datatable that I am working on: http://jsbin.com/OJAnaji/15/edit I initially populate the table with data and display it. Then, I add a new column called "kontrole." data = google.visualization.arrayToDataTable([ ['Name', &apo ...

Is the server's performance improved by routing through Angular instead of using Express for routing?

I'm currently working on developing a web application and I've been thinking about using client-side JavaScript (Angular) for routing. I believe that by routing through Angular, it could potentially speed up my application by reducing the number ...

Steer your keyboard attention towards the parent element that embodies a list

My implementation focuses on making drop down menus accessible via keyboard input using HTML/CSS and JS/jQuery events. The goal of keyboard accessibility includes: Tab key to navigate the menu elements. Pressing the down arrow key opens a focused menu. ...

Utilizing Angular to Refine Arrays

I am currently working on filtering an array called courses by a property known as FacilityId. In my controller, I have set up $http calls that return responses for the following: function holeIndexController($scope, $http) { $scope.facilities = []; ...

Encountering a syntax error with JSON.parse() when using MVC 4 Razor with Jquery Ajax

I am encountering an issue with my MVC 4 application login page. I am attempting to utilize a jQuery ajax request to my login controller to check if the user exists. Here is the snippet of my jQuery code: $(document).ready(function () { $("#btnSub ...

Could you walk me through the details of this React function?

Currently, I have a function in place that retrieves products from the database to display on the eCommerce website's product page. Now, I am working on creating a similar function for user sign-in. Could you lend me a hand with this? I'm still ...

AngularJS: "length" method fails to include the space character at the end of a string in its count

When attempting to count the length of a string ($scope.count = $scope.str.lenght), I noticed that if there is a space at the end of the string, it is not included in the count unless there is a character following the space. Example: "Hello " = 5, " ...

How can I achieve a smooth opacity transition without using jQuery?

Although I understand that JQuery offers functions for this purpose, I am interested in finding a solution using only pure javascript. Is there a way to change the CSS opacity setting over time? Perhaps utilizing a unix time stamp with millisecond precisi ...

Once the PHP page loads, it becomes challenging for me to dynamically change values in JavaScript

Within my code snippet below, I am aiming to modify the initial value using a slider. The slider appears to be functioning correctly; however, it is not updating the values of timeout as indicated beneath the line $('ul.<?php echo $this->session ...

Disabling the default validation message in HTML form inputs

Is there a way to change the default message that appears when submitting an empty HTML text input? I would like the box border to turn red instead. Can anyone help me achieve this? Below is the code for the text input box: <div class="input-group ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...

Attention: The PageContainer component requires React component classes to extend React.Component

I recently started using react-page-transitions in my project and encountered the following warning message: "PageContainer(...): React component classes must extend React.Component." Here is a snippet of my code: import React from 'react'; ...

Using enzyme mock function prior to componentDidMount

When it comes to mocking a function of a component using Jest, Enzyme, and React, the process typically involves creating a shallow wrapper of the component and then overloading the function as needed. However, there seems to be an issue where the componen ...