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

Having trouble with an onClick function not working on a .php webpage?

I recently developed a simple JavaScript script that dynamically loads an image based on user input in a text field (e.g., entering 'brick1' loads brick1.jpg). Although this works fine on a regular HTML page, I faced issues triggering the onClick ...

What is the best way to achieve a full width table in an HTML format on a smartphone browser?

Apologies for my limited English proficiency. I am currently working on creating a horizontal scrollable table in HTML. My goal is to make the width of the table span beyond the browser's viewing area, so that sticky cell functionality can be implem ...

React Error: Invalid Element Type with Named Exports

I've been diving into the world of React hooks and functions, working on three different files. First, there's one that establishes a context called SummaryContext. The second file contains a class component that consumes this context named WikiS ...

The Angular bootstrap datetimepicker doesn't support disabling past dates

Has anyone successfully disabled past dates on an angular bootstrap datetimepicker before? I've tried using the date-disabled attribute, but I can't seem to get it to work. <datetimepicker class="calendar-format" data-ng-model ...

Sending the results from a Vue.js component to a text input field in HTML

Using vue.js and the v-for function to read QR codes has been a challenge for me. For example: <ul v-for="(scan,key) in scans" :key="key" > {{scan.content}} </ul> I need to extract the value inside {{scan.content}}, like an EmployeeID, but I ...

The issue with the left border color not functioning in JavaScript

Attempting to alter the border-left-color property using this script is resulting in a Uncaught SyntaxError: Unexpected token -. Is border-left-color actually supported? Javascript function logoChange() { var description = new Array (); description[0] ...

What is the best way to send data via the HTTP POST method in AngularJS?

I have a situation where I am using the same HTTP method in different controllers as shown below: Service: var method="sampleMethod" HotalStatisticService.GetReservations = function (data) { return $http({ method: 'POST' ...

A guide on seamlessly combining AngularJS and ASP.NET Web API

As a newcomer to AngularJS and ASP.NET, I have been struggling to find the right answers and am feeling more confused than ever. My current challenges include: 1) How can I seamlessly integrate an AngularJS application with an ASP.NET MVC web API using S ...

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...

Is there a specific method for organizing cached buffer conversions in Node.js for optimal efficiency?

In a GitHub discussion, it was pointed out that the Map's .has method does not work with buffers because identical buffers are considered as distinct objects. This limitation became apparent when attempting to store buffer string conversions in a map ...

Ingesting RSS feed into an Express server

I've been searching for hours, but I just can't seem to find a solution. I was able to figure things out when working on the client side, but now that I'm trying to load posts on the server and render them in the view, I'm hitting a roa ...

Unlock the powers of Express, Passport, and Redis sessions!

Lately, I have been utilizing the default MemoryStore for my Express sessions and everything has been running smoothly. However, I encountered a setback where all session data was lost between restarts. To address this issue, I am now attempting to configu ...

Connecting the search results page with the specific details page

Currently, I am developing a results page for my website and require assistance with linking each restaurant to a detail.php page. The project involves showcasing all the restaurants in San Francisco along with their health inspection scores, address, and ...

Avoid refreshing the page when clicking on an anchor tag in Vue.js

I have the code below in my Vue file. The problem I am encountering is that the page reloads whenever I click on the link. I have tried using event.preventDefault() but it did not solve the issue. Can someone please help me identify what I am doing wrong ...

Creating a Duplicate of the Parent Element and its Child Elements using jQuery

Here is a code snippet I have that adds a new paragraph when a button is clicked. Currently, the script clones the "sub" div and appends it to the "main" div. However, the issue is that it only copies the content of the "inner" div within the "sub" div ins ...

Transforming Angular models into formatted dates

I am having trouble formatting a datetime object obtained from an ng-model for display on an input field. Despite checking the code and verifying that the date is correctly formatted, it still does not display as expected. Can someone shed some light on th ...

Unable to process JSON array

One issue I'm facing is with an 'onload' handler for my web page. The javascript function 'handleLoad()' that it calls has suddenly stopped working, specifically not being invoked after attempting to pass the output of json_encode ...

Assigning a CSS class during the $routeChangeStart event does not activate the animation, unless it is placed within a setTimeout function

Just dipping my toes into Angular, so feel free to correct me if I'm way off base here. I've been working on animating the clamps on both sides of my website to slide in upon the initial page load. You can check out the live version at: Current ...

What methods can I use to conceal #! from showing on the browser's address bar?

Imagine you have the below link: www.someurl.com/#!?page=index How would you convert it into one of these options: www.someurl.com/#!/index (using mod_rewrite) www.someurl.com/ajax/index (also using mod_rewrite, but replacing #! with ajax) www.someurl. ...

The deployment on heroku encountered an error during the build process

I'm attempting to deploy my React application on Heroku, but I keep encountering the following errors: -----> Installing dependencies Installing node modules npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ...