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

Ways to release a client-side script with npm?

Within my nodejs package, I have included code that can be executed on both the backend and in a single .js file for browsers. In order to utilize the browser script, it must be placed within a script element in an HTML file. My query pertains to whether t ...

Running an npm audit on the project reveals numerous errors and vulnerabilities

After running npm audit on my React project, I was presented with an extensive list of issues that needed attention. # npm audit report postcss 7.0.0 - 8.2.9 Severity: moderate Regular Expression Denial of Service - https://npmjs.com/advisories/1693 fix ...

Encountering a 404 error in Angular MVC project while trying to load a

Trying to access an edit partial named AddEditPersonModal.cshtml from a different folder in my MVC project, in order to load its contents into a UI Bootstrap modal using Angular. However, when the index.cshtml page loads, I encounter a 404 error related to ...

Is it possible to automatically redirect to a different URL if the server is running slow when clicking?

Is it possible to utilize Javascript, AJAX, or another client-side technology to automatically redirect the user to a different URL if the initial URL is slow to respond when clicked on? For example, if a link redirects to URL1 and there is no response fr ...

Issue with onClick event not firing when using option tag in React

onClick event seems to have an issue with the <option> tag. How can we successfully use the onClick event with the select option tags while assigning different parameters to each option? async function setLanguage(language) { ...

HTML - Using Tables to Add and Edit Rows

Take a look at this demo on JSFiddle for my project: Demo jsfiddle I'm currently in the process of creating a table with various functionalities. The function "sortTable" is responsible for sorting the table and it's functioning as expected. T ...

What steps do I need to take to transform this click event function into one that is triggered automatically upon the div loading?

In order to automatically load content into a div using innerHTML, the PHP file must be retrieved and the div updated with its content. Within this div is another one labeled "tweet" which displays actual tweets based on a specific hashtag provided through ...

What is the method for accessing extra parameters in the signIn() callback function in [...nextauth]?

As per the Next Auth documentation, it is possible to pass extra parameters to the /authorize endpoint using the third argument of signIn(). The examples provided are: signIn("identity-server4", null, { prompt: "login" }) // always ask ...

Vue warning: Issue encountered in created hook - Attempting to access property 'get' of an undefined variable is causing a TypeError

I encountered an error while using axios: [Vue warn]: Error in created hook: "TypeError: Cannot read property 'get' of undefined" export default { methods: { loadUsers(){ axios.get("api/user").then(data => ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Unable to create selected buttons in Vue.js

I'm having trouble creating buttons that can select all options when clicking on either size or color. The buttons aren't showing up at all. Can someone help me identify the issue? I've attempted various solutions but none seem to work. Any ...

Exploring Facebook Graph API response with Angular 2 Mapping

I am using HTTP calls to access the Graph API in order to retrieve posts from a Facebook page. Here is the code snippet that fetches an array of posts: let url = 'https://graph.facebook.com/15087023444/posts?fields=likes.limit(0).summary(true),comme ...

If a DOM element contains any text node, completely remove the element

Currently, I am using WordPress and my theme automatically generates a menu where all the items are marked with "-". It can be quite annoying. I have tried to fix it by replacing all the option values instead of just removing the "-", but I couldn't g ...

Enhance data table by displaying a set number of rows that do not completely fill the table's height

I'm currently attempting to implement a v-data-table with fixed header and footer. However, I've encountered an issue where if I set the table height to be larger than the row height, the table takes on the defined height and the footer ends up b ...

Exploring the capabilities of require() in nodeJS

I'm wondering about the inner workings of the require() function in a nodeJS application. What exactly does require() return? Let's say I want to utilize two third-party packages: lodash and request. After installing these packages, my code mig ...

Converting HTML widget code to NEXTjs code for integration in an application (CoinMarketCap Price Marquee Ticker)

Having trouble integrating the CoinMarketCap Price Marquee Ticker Widget into my NEXTjs app. I'm outlining my process and hoping for some suggestions from others who may have attempted this. Template Code: To embed the widget in an HTML page, here is ...

Encountering an error in accessing my own API: "Cannot read property 'then

I'm currently in the process of using my personal express.js API with nodejs. Although it is functioning, I am encountering an error that is preventing me from accessing the response of the request. Below is a snippet of my code: routes.js: app.post ...

Amazon S3 Landing Page Featuring Contact Form

Although S3 is not a fileserver, it serves as an excellent tool for managing static websites. The majority of my projects are 99% static, making it ideal for this particular project. As an AWS Solutions Architect, I am struggling to find the most straightf ...

Can anyone figure out why this code is not functioning properly? It seems to be targeting the body element and all of

Currently, I am utilizing jqtouch to create a mobile website. In addition to this, I am incorporating a gallery image slider into the website. However, I have encountered an issue where the images do not display when placed between <div id="project_name ...

Accessing React Context globally using the useContext hook

I'm feeling a bit puzzled about how the useContext hook is intended to function in a "global" state context. Let's take a look at my App.js: import React from 'react'; import Login from './Components/auth/Login'; import &apos ...