Looping through an array of items in a for loop with a chain of

I want to ensure that the for loop is successfully executed and then the result is passed to the next function:

FindIdsRequests =  function(){
    results = $scope.requests
    var deferred = $q.defer();
    var promise = deferred.promise;
    var array = []
    for (var i in results) {
        promise = promise.then(function(){
            array.push(results[i].uid)      
        })
        return promise
    }
    return promise.then(function(){
        return array
    })
}

$scope.ConfirmRequests = function(){
    //alert('req'+JSON.stringify($scope.requests))
    FindIdsRequests().then(function(array){
        alert('arr'+JSON.stringify(array))
    })
})

It seems that the FindIdsRequests function should be returning the result of the for loop, but it doesn't (the alert message is not displayed, so it seems not to be reaching that point). Any suggestions?

Answer №1

Challenges:

  1. Each iteration of the loop is replacing the previous promise, resulting in only one promise existing at a time
  2. Without resolving the promise, the then() function will never be triggered, leaving the array empty
  3. A return statement within the loop causes it to break after the first iteration, preventing it from completing
  4. If this were an asynchronous process, the value of i would not be what you expect inside the then() function due to the promise resolving after i has finished

It seems unnecessary to write this code considering it is synchronous and does not require the use of promises

Answer №2

Instead of returning a promise, you can leverage the $q service in the following way:

$q.all([promise1, promise2]);

For instance:

FindIdsRequests =  function(){

    var requests = $scope.requests;
    var results = [];    
    var array = [];

    for (var i in requests) {

        var req = $http.get('http://someUrl.com/' + requests[i].uid);

        array.push(req);

        req.then(function (response) {
            results.push(response.data);
        });
    }

    return $q.all(array).then(function(){
        return results;
    });
}

This piece of code will provide a promise that resolves once all promises in the array have resolved.

Answer №3

Appreciation goes out to @charlietlf for the helpful comments. I've made some adjustments based on the feedback and now the code is functioning properly:

FindIdsRequests =  function(){

    results = $scope.requests
    var deferred = $q.defer();
    var promise = deferred.promise;
    var array = []
    for (var i in results) {
        alert('www'+JSON.stringify(results[i].uid))
        var obj = results[i].uid
        promise = promise.then(function(){
            array.push(results[i].uid)      
        })
        //return promise
    }
    deferred.resolve(array)
    return promise.then(function(){
            alert('ee'+JSON.stringify(array))
            return array
     })
}

It seems I had forgotten to include the resolve function, which was causing the issue.

Answer №4

Creating a Chain of Promises from an Array of Promises

Utilize $.when to initiate an empty promise and employ a for loop to construct a chain:

function chainPromiseArray(promiseArray){
    var promise = $q.when();
    var array = [];
    for (var i=0;  i < promiseArray.length; i++) {
        promise = promise.then(function(){
            var derivedPromise = promiseArray[i].then(function(result) {
                //push data
                array.push(result.data);
            });
            //return promise to chain
            return derivedPromise;
        });
    };
    var finalPromise =  promise.then(function(){
        return array;
    });
    return finalPromise;
};

The example above initializes with an empty promise and progresses through a chain stemming from that initial promise. The final promise will result in the array generated by the chain.

Chaining promises

As the .then method of a promise generates a new derived promise, it is feasible to construct a series of promises. These chains can vary in length, and since a promise can resolve with another promise (thus deferring its resolution), it becomes viable to pause or defer the resolution of promises at any point within the chain. This functionality enables the implementation of robust APIs.

--AngularJS $q Service API Reference -- chaining promises

The sequential execution of promises is demonstrated in the example provided. For simultaneous execution of promises, consider utilizing the $q.all method.

Answer №5

The FindIdsRequests() function showcased does not contain any asynchronous elements in the code, making it suitable for a synchronous operation. Attempting to introduce promises into this function could unnecessarily complicate a straightforward task:

// Retrieve an array of unique identifiers (uid) from $scope.requests
function FindIdsRequests() {
    return $scope.requests.map(function(item) {
        return item.uid;
    });
});

$scope.ConfirmRequests = function() {
    var ids = FindIdsRequests();
    console.log('Array of IDs: ' + JSON.stringify(ids));
})

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

Serve static files from parent directories using Express.js

Currently facing some issues serving static files with expressJs. Directory structure: public css lib src views home index.html server.js In my index.html, all assets are prefixed with a leading slash. Static file setup: app.use(express.static ...

Why is my model binding acting strangely?

My AngularJs application interacts with a RESTful web service using the $resource module. The data retrieved from the resource (salesOrderResource) is stored in the model's vm.rowData. When I log this data to the console within the resource's que ...

"Utilize JavaScript to extract data from JSON and dynamically generate a

I'm currently facing an issue with reading JSON data and populating it in my HTML table. The function to load the JSON data is not working as expected, although the data typing function is functioning properly. I have shared my complete HTML code alo ...

Having trouble getting your custom Angular directive to function properly with dynamically changing images?

Currently in the process of developing a custom directive for AngularJs that involves an image rotator based on a Jquery Plugin I created, you can check it out here Below is the code snippet for my directive: .directive('imageRotator', function ...

Setting up Nginx to support html5mode in your web application involves making adjustments to the

When using AngularJS for clean URLs, I need to implement $locationProvider.html5Mode(true);. However, upon refreshing the page, I encounter a 404 error. I have come across suggestions to configure the server file accordingly. Directory Structure: /html ...

How to Remove onFocus Warning in React TypeScript with Clear Input Type="number" and Start without a Default Value

Is there a way to either clear an HTML input field of a previous set number when onFocus is triggered or start with an empty field? When salary: null is set in the constructor, a warning appears on page load: Warning: The value prop on input should not ...

Creating a Python server for an Angularjs application and capturing user input

Can you offer me some assistance, whether it's just a hint or a useful tip that could improve my current approach? I have created a series of forms using HTML and AngularJS. Each form collects input data from users, which is then stored in a JSON str ...

Utilize JQuery to modify hover state when focused and restrict tab navigation to specific areas on the keyboard

I'm currently working with a JQgrid in one of my projects (Check out the JFiddle here). and I have some specific requirements: 1.) I want the save & cancel button to become highlighted when a user tabs to it, similar to how it behaves on mouse ov ...

Detection of NTLM error during the parsing of the Authorization header

After posting a question here, I discovered that the issue causing the error was not related to my axios request. Unfortunately, I'm unsure how to close the question. An error occurs when attempting to send an Axios Get request to my express backend ...

Creating a dropdown navigation menu using jQuery

I have been experimenting with creating a customized Drop Down menu using ul li and Jquery, following this helpful Tutorial. Here is the sample HTML Code for testing: <div id="dd" class="wrapper-dropdown-3" tabindex="1"> <span>OS</span> ...

The popover displays the text "[object Object]" when triggered by an ajax event

Upon observing the image, I noticed that my bootstrap popover is triggering and displaying “[object Object]” instead of the database data I retrieved. After adding logs to the JavaScript AJAX code, I can see that the data is being retrieved, but it i ...

Issue with callback function not triggering after comment deletion in REACT

Although I am successfully able to delete the comment, I am facing an issue where the callback function is not being invoked. My suspicion is that it might be related to how I pass multiple arguments to the function, but I cannot confirm this. Below is th ...

Navigate the div with arrow keys

Looking for an answer similar to this SO post on moving a div with arrow keys, could a simple and clear 'no' be sufficient: Is it possible to turn an overflowing div into a "default scroll target" that responds to arrow-up/down/page-down/space k ...

Comparison of WebAPI Response Codes: Understanding the Difference Between 401 and

As a part of my learning project, I am developing a WebAPI and striving to implement best practices. The initial focus is on creating an authentication API that accepts an authentication object in JSON format: { username: myusername, password: mypa ...

Incorporating Subtitles into Videos using NodeJS and the FFMpeg Fluent API

I'm having trouble adding subtitles (srt) to a video stream using Node JS and FFMpeg... Here's what I've tried: var command = ffmpeg(file.createReadStream()) .input("C:\\code.srt").videoCodec('copy') .videoCodec(& ...

Express is encountering a non-executable MIME type of 'text/html' with Webpack

My express application setup is as follows: const express = require("express"); const app = express(); const server = require("http").Server(app); const path = require("path"); const port = process.env.PORT || 5000; app.use(& ...

Having trouble getting the Babel plugin transform-remove-console to function properly with the Vue CLI 4 and @vue/cli-plugin-babel/preset?

When you create a VueJS project using Vue CLI 4, Babel is configured with a useful preset in babel.config.js: module.exports = { presets: [ '@vue/cli-plugin-babel/preset', ], }; I am attempting to use babel-plugin-transform-remove-conso ...

What method can be used to incorporate Google Places API into a .js file without using a <script> element?

As I delve into the Google Places API documentation, I noticed that they require the API be loaded in this format: <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script> Is ...

Error: The 'filename' property of undefined cannot be read when attempting to upload a user profile photo using multer

I am facing an issue while attempting to upload a user profile photo using express.js server and Multer. I keep receiving the error message "TypeError: Cannot read property 'filename' of undefined." Below is the code snippets for both the server- ...

Implementing a scroll wheel type date and time picker similar to iOS in an Ionic1 app

Trying to incorporate a date time picker in ionic1, but struggling to achieve the format shown in this image ("mm/dd/yyyy HH:00 P") such as 12/31/1899 12:00 AM. While there are various date/time options for ionic2 and 3, I have not been able to find this s ...