Obtain the final result once all promises have been successfully resolved in a loop

Here is an array of IDs:

let idsArray = [1, 2, 3, 4, 5];

How can I ensure that a promise is returned only after all calls made within the loop are completed?

            let deferredPromise = $q.defer(),
                finalResult = [];

            for (let i = 0; i < idsArray.length; i++) {
                let id = idsArray[i];

                Tools.remove(id).then(function(response) {
                    finalResult.push(response.id);
                }).catch(function(errorResponse) {
                    finalResult.push(errorResponse)
                });
            }

            deferredPromise.resolve(finalResult);

            return deferredPromise.promise;

Answer №1

If you're in search of $q.all, a method that allows you to wait for an array of promises, here's one way to approach it:

return $q.all(array.map(Tools.remove)).then(function(results){
    return results.map(function(result){ return result.id; });
});

Many other solutions provided have unnecessary complexities and rely on patterns that are deemed as anti-patterns within JavaScript or promise handling. This simple solution involves mapping each item to Tools.remove, waiting for the results, extracting the IDs, and returning them.

Answer №2

It seems like your goal is not to simply hand back a promise once all tasks are completed, but rather to resolve it.

You may need to create a custom method for keeping track of the number of asynchronous calls still pending. One approach could be using a basic integer counter: increase it each time you initiate an async call, decrease it each time one completes. Upon completion, if any async call detects a count of 0, it can infer that it is the final async call and proceed with the next phase of execution.

To illustrate this with your specific scenario:

var taskCount = 0;
for (var j = 0; j < elements.length; j++) {
            var elementID = rows[j];

            taskCount++;
            Tools.delete(elementID).then(function(outcome) {
                outcome.push(outcome.id);
                taskCount--;
                if(taskCount === 0) invokeNextStep();
            });
        }

If concerns arise regarding overlapping responsibilities, consider transforming this into an async-manager entity.

Answer №3

Here's my approach :)

let list = [7, 8, 9, 10, 11];
let output = [];
let deferral = new $.Deferred();

let deferredList = $.map(list, function(id){
    
    let operationDeferred = Tools.executeOperation(id);

    operationDeferred.done(function(result) {
        output.push(result.id);
    }).catch(function (response) {
        output.push(response)
    });

    return operationDeferred;
});

$.when(deferredList).then(function(){
    deferral.resolve(output);
});

return deferral.promise(); 

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

Tips for accessing a unique window name in JavaScript

How can I make window.name persist between page refreshes? I need to use window.name to differentiate between multiple browser windows, allowing each one to display distinct data while sharing the same URL. However, my problem is that the value of window ...

Retrieving JSON data using Jquery (undefined)

When attempting to retrieve a value from JSON data, I am receiving 'undefined'. $.get( baseURL + 'vacation/show/' + name_surname, function( data ) { alert(data); // returns [{"id":"1","title":"Testas","start":"2015-03-04","end":"20 ...

How to effectively test a form submission with an external API using React, Jest, and Enzyme?

I have integrated a geocoding API to verify address submissions on a form. Upon submitting the form, the geocoding API is called first, followed by validation of the remaining form fields. class Form extends React.Component { geocode = (streetAddress, cit ...

Leverage JavaScript to showcase Django object on the webpage

I am trying to achieve the following using javascript: when a row is clicked, it should retrieve the index and display the object at that index. This functionality works in a django template. <div>{{ project.0.customer_name}}</div> <div> ...

What is the best way to incorporate jQuery code into a specific page on a WordPress site?

I am struggling with adding jQuery to a single WordPress page for a script I have. Despite my efforts to find solutions, I find them difficult to grasp. <script> $(document).ready(function(e) { $('#checkboxtest').change(function(){ if( ...

How can Chrome's display:none latency be eliminated?

My Chrome extension is designed to alter a third-party web page by removing a button and adding two new HTML elements. The process involves observing the URL of the current tab and executing an HTML injection if it matches the specified regex pattern. Desp ...

Leveraging the local variables within a function in conjunction with the setTimeout method

Currently, I'm facing an issue with a website that I'm working on. I have created a function that should add a specific class to different ids in order to make images fade out one by one on the home page. To streamline the process, I used a local ...

Utilize Vue Component by assigning a computed property to the data source

Trying to assign a computed property value to a component's data in order to fetch and manipulate localStorage data. After mounting the component, I want to monitor changes in the localStorage. If my key is updated, I need to retrieve the new value, ...

How can data tables be generated using AJAX, JSON, HTML, and JS?

HTML: <table> <tr> <th>Student Name</th> <th>Student Grades</th> </tr> <tr> <td> <select name="dropdown" id= ...

"Troubleshooting ways to resolve babel-eslint import/export issues without the need for a configuration

Upon running npm start, I encountered the following error message: Parsing error: 'import' and 'export' may only appear at the top level After investigating this issue, suggestions included updating the eslint configuration file with ...

Share content on Facebook using a single-page application

This inquiry may not be specifically tied to a particular software stack, framework, or coding language. In the current project I'm working on, we are utilizing AngularJS for developing the front-end with a static landing page that loads real data an ...

Implement a loader in AngularJS to display when transitioning between pages

Is there a way to implement a loader that appears when the page starts changing and only disappears once the entire page is fully rendered to prevent clipping bugs? I have already set up the loader as shown below: $scope.$on('$routeChangeStart' ...

Pass the response from a JavaScript confirm dialog to a Ruby program

Apologies if this question seems naive, but I am curious if it is feasible to pass the response from a JavaScript confirm box or message box as a value to a Ruby program. If I were to click on the "yes" button in the confirm box, could this response be st ...

Unable to employ Javascript while utilizing AJAX within jQuery Mobile

Exploring the potential of Swiper Javascript Api from within Jquery Mobile raises some challenges. The compatibility issues with Ajax in Jquery Mobile complicate the execution of Javascript functions. This becomes evident when examining example source cod ...

Images set as the og:image on the following 14 websites hosted on Vercel require authentication to be displayed

After deploying my Next.js 14 site on Vercel, I placed opengraph-image.png in the app folder alongside layout.tsx. Upon inspecting the meta tag, I noticed the following: <meta property="og:image" content="https://ns-website-6pnvd8ili-mare ...

Print custom jQuery attribute to console or log output

I need help retrieving and displaying a custom jQuery attribute in either an alert or console. Despite attempting to use console.log() to access my custom data attribute, I am unable to see its value appear. The specific value I am trying to display is d ...

Leveraging the power of AJAX to dynamically update information on a modal form using PHP's

After successfully preventing my modal form from closing upon submitting a value using ajax jQuery without refreshing the page, I encountered a new issue. Whenever I fill in my modal form and click submit to update the data inside my database, it does not ...

Having completed "npm link" and "npm i <repo>", the module cannot be resolved despite the presence of "main" and "types" in the package.json file

Here is the contents of my package.json file: { "name": "ts-logger", "main": "dist/index.js", "types": "dist/index.d.ts", "scripts": { "install": "tsc" ...

The error message "TypeError ".deploy" is not a function in your Hardhat environment."

Currently, I'm in the process of developing a page for minting NFTs called astro-mint. To move forward, I need to deploy my contract using hardhat. However, when I execute this command npx hardhat run scripts/deploy.js --network dexitTestnet An erro ...

What is the purpose of <Component render={({ state }) => {} /> in React?

Currently delving into the world of ReactJS, I decided to implement fullPageJS. It seems to be functioning properly, although there are certain syntax elements that remain a mystery to me. Take a look at the component below: function home() { return ( ...