Is there a way to specifically call the last promise in a loop?

I'm new to promises and could use some help. I have a situation where promises are resolving randomly, how can I ensure that the last promise in the loop is resolved after the full loop executes?
For example, if this.selectedValues has 4 values, sometimes only three get updated and sometimes all four get updated. This inconsistency is due to promises.

let promise;
private values: Object[] = [];
_.each(this.selectedValues, (selectedValue) => {
    promise = that.valueService.getValuesForName(selectedValue).then((pg) => {
        values.push({
            Id: pg.Id,
            Name: pg.Name,
            Description: pg.Description,
            Policies: pg.Policies
        });
    });
});

if (promise !== undefined) {
    promise.then(() => { // I want to call the promise only once for the last index
        let data: Object = {
            Id: that.id,
            Name: name,
            Description: description,
            Values: values
        };
        that.updateEdit(data, name);
    });

Answer №1

let promiseReq = Promise.resolve();
const storedValues: Object[] = [];
_.each(this.selectedValues, (selectedVal) => {
    promiseReq = promiseReq.then(function() {
        return that.valueService.getValuesForName(selectedVal);
    }).then((pgData) => {
        storedValues.push({
            Id: pgData.Id,
            Name: pgData.Name,
            Description: pgData.Description,
            Policies: pgData.Policies
        });
    });
});

if (promiseReq !== undefined) {
    promiseReq.then(() => { // ensuring promise is called only once for last index
        const updatedData: Object = {
            Id: that.id,
            Name: theName,
            Description: theDescription,
            Values: storedValues
        };
        that.updateEdit(updatedData, theName);
    });
}

Answer №2

Appreciate your response, my issue has been resolved thanks to $q finally coming through for me.

 let promise,promises=[];
private values: Object[] = [];
_.each(this.selectedValues, (selectedValue) => {
    promise = that.valueService.getValuesForName(selectedValue).then((pg) => {
        values.push({
            Id: pg.Id,
            Name: pg.Name,
            Description: pg.Description,
            Policies: pg.Policies
        });
    });
      promises.push(promise);
});

 let combinedPromise = this.$q.all(promises);
if (combinedPromise !== undefined) {
    combinedPromise.then(() => { // ensuring promise is only called once at the end
        var data: Object = {
            Id: that.id,
            Name: name,
            Description: description,
            Values: values
        };
        that.updateEdit(data, name);
    });

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

Forwarding parameter data type

I am facing an issue with 2 navigation points leading to the same screen 1. this.router.navigate([this.config.AppTree.App.Module.Details.Path], { state: { data: { id: this.TableId } } }); this.router.navigate([this.config.AppTree.App.Module.Details.Pa ...

What do the letters enclosed in brackets signify?

I am currently working with a library known as Monet.js, and within the documentation, there are descriptions that look like this: Maybe[A].map(fn: A => B) : Maybe[B] I am unsure of what the letters inside the brackets stand for. Is there anyone who c ...

Steps for modifying the CSS class of an <a> tag with Jquery/Javascript

I am attempting to dynamically change the class of a tab on the dashboard based on the selected page. In the dashboard, there are 3 tabs: <div> <ul class="menu"> <li class="MenuDashboard"><a href="#" >Dashboard</a&g ...

Utilizing AngularJS and Bootstrap popover: A guide to effectively implementing "popover-is-open" within an ng-repeat loop

When utilizing ng-repeat to generate a table with items, each item has a button in its row that opens a popover for editing the object. I want to avoid using the click-outside property of the bootstrap popover because I only want the popover to close when ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

The AngularJS error message: TypeError: Unable to access the 'images' property because it is undefined

Currently using AngularJS version 1.5.11 I am attempting to present images sourced from a JSON array. Is my method correct: $scope.mainImage = $scope.template.images[0].name;. The issue arises at the line where it says it cannot read property of images. ...

How can I use Ajax to open views in Asp.net Core 3.1?

Why is the view not being displayed even though there is no error? jQuery : $('#edit_button').on("click", function () { var instance = $('#jstree').jstree("get_selected"); if (instance != 0) ...

Update the displayed locations on Google Maps by fetching and displaying marker data

I am able to retrieve and display information from my MySQL table, but I need assistance with refreshing this data every 5 seconds using my current code. The data being shown is not extensive, just about 5 or 8 markers at a time. Below is the code I curren ...

What is the best way to include numerous attributes to an element using JavaScript?

Attributes can be included within a string in the following format: let attr = ' min="0" step="5" max="100" '; or let attr = ' min="2019-12-25T19:30" '; and so on. Is there a function available ...

Concealing a Div on Click Outside of Child Div in ReactJS

I have a parent div with a child div in the center. I am trying to figure out how to close the parent div only when clicking outside of the child div. My current code is structured like this, using triggerParentUpdate to control whether the div should be d ...

The data from my API is not showing up in my React application

Im working on a project where I am trying to retrieve an image of a recipe card from and display it on my react.js application. However, I am encountering difficulties in getting the API data to show up on the page when running the code. Any assistance wo ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

The process of filtering and outputting JSON data in JavaScript or jQuery

There is JSON data available for review. var data = [{ "gender": "male", "name": { "first": "rubween", "last": "dean" } }, { "gender": "male", "name": { "first": "rubween", "last": "dean" } }, { ...

How can I retrieve the offset top of a td element in relation to its parent tr element?

Here is some sample dummy HTML code: <table> <body> <tr> <td id="cell" style="height: 1000px; width: 200px;"></td> </tr> </body> </table> I am looking to attach a click event ...

What is the best way to erase information displayed when hovering over an element using mouseout?

Whenever the user hovers over an image, an information box appears regarding that specific image. The information inside the box changes as I move over another image, but when not hovering over any images, the information box remains visible. Unfortunately ...

A step-by-step guide to adding an object to an already existing array in Vue.js

Within the code snippet below, I am dealing with an object value and trying to figure out how to push it to an existing array. methods: { onChange(event) { this.newItems.push(event.target.value); console.log(event.target.value); } } Here is m ...

What is the best way to invoke an API two times, passing different parameters each time, and then merge both responses into a single JSON object using a callback function?

This code snippet is currently functional, but it only retrieves the JSON response for the first set of parameters. I am looking to make multiple calls to an external API with different parameters and then combine all the responses into one concatenated J ...

JavaScript Scroller that keeps on scrolling

Unique Continuous JavaScript Scroller I am currently working on a JavaScript scroller script that enables left to right and right to left scrolling on the click of next and previous buttons. The script is designed to work with 1 to 3 div elements in a con ...

Using JSON object as an argument in React functional component

Currently, I'm trying to assign a JSON object to a const variable. I've been successful with using vars in the past, like so: {this.props.user.map(function(user){... However, when it comes to stateless consts, I'm encountering some confusi ...

Issue: Module 'xml2json' not found

Encountered an error while running my project package. When I tried to install the necessary packages using npm install xml2json I still encountered another error below. Can anyone provide suggestions or ideas on how to resolve this issue? D:\xa ...