Waiting for Angular's For loop to complete

Recently, I encountered a situation where I needed to format the parameters and submit them to an API using some code. The code involved iterating through performance criteria, performance indicators, and target details to create new objects and push them into an array before making the API call.

                for (let a = 0; a < perfCriteria.length; a++) {
                    const element = perfCriteria[a];
                    let newObject = Object.assign({}, paramObject)
                    newObject.performanceCriteria = element.performanceCriteriaId
                    for (let b = 0; b < element.performanceIndicators.length; b++) {
                        const element2 = element.performanceIndicators[b];
                        let newObject2 = Object.assign({}, newObject)
                        newObject2.performanceIndicator = element2.performanceIndicatorId
                        newObject2.numberTarget = element2.divisionTarget ? element2.divisionTarget : ""
                        newObject2.targetDetails = element2.targetDetails
                        for (let c = 0; c < element2.targetDetails.length; c++) {
                            const element = element2.targetDetails[c];
                            element2.targetDetails[c].individualAccountable = element.individualAccountable.map(function(row){
                                return row._id
                            })
                        }

                        divTargetArray.push(newObject2)
                    }
                }

                this.DivisionTarget.create(divTargetArray).subscribe(result =>{
                    console.log('result', result)
                    if(result.success){
                        this.appComponent.showLoadingIndicator = false;
                        this.router.navigate(['/index/app/performanceManagement/divisionTargets']);
                        this.toastService.openSnackBar(result.message, "success");
                    }else{
                        this.appComponent.showLoadingIndicator = false;
                        this.toastService.openSnackBar(result.message, "danger");
                    }
                }, error => {
                    this.appComponent.showLoadingIndicator = false;
                    this.toastService.openSnackBar(error, "danger");
                });

Despite the functionality of the code, there have been instances where it doesn't wait for the For loop to finish before proceeding with submitting the data to the API. Is there a method or technique that can ensure the completion of the For loop before moving forward with the API submission?

Answer №1

After examining your code, it appears that there are no asynchronous operations present, indicating that the code is likely executed sequentially, line by line. It seems improbable that the subscription occurs before the loop has finished running. The root of the issue may lie elsewhere in the code.

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

Issues with JQuery script causing inconsistency in checking checkboxes

My code includes two functions designed to check and uncheck all checkboxes with a specific class. Initially, the functions work as expected but upon subsequent attempts to run them, the checkboxes do not function properly. Instead, the HTML code seems to ...

Prevent specific fields from being saved in Node MongoDB native

When working with MongoDB and using the node mongodb native driver to insert documents, I have encountered an issue. The objects I am inserting have fields that I do not want to be saved in the database: var x = { field: 'value', _nonPersist ...

Separate a string using commas but disregard any commas inside quotation marks

Similar Question: JavaScript code for parsing CSV data There is a string that looks like this: "display, Name" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d49584e49135e5250">[email protected]</a> ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

Ways to "Compile out" log commands

In my typescript project, there is a section of code dedicated to creating debug information. However, upon profiling the application, I discovered that this debug code is causing a significant performance impact. Currently, my approach involves setting a ...

Ways to get a Discord bot to echo a message?

As a novice in the world of discord.js and bot creation, I am eager to implement a simple magic 8-ball inspired command. This command will allow users to ask the bot a question and receive a random answer in response. const commands = [ new SlashCommandBui ...

You are unable to apply 'use client' on a layout element in Next.js

While attempting to retrieve the current page from the layout.txt file, I encountered errors after adding 'use client' at the top of the page: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data parseMod ...

Is it possible for me to create a lineString connecting two points in OpenLayers3?

I need to create a lineString connecting my two given points, such as [-110000, 4600000] and [0, 0]. ...

Callback for dispatching a union type

I am currently in the process of developing a versatile function that will be used for creating callback actions. However, I am facing some uncertainty on how to handle union types in this particular scenario. The function is designed to take a type as inp ...

What is the reason behind permitting void functions in the left part of an assignment in Typescript?

Take a look at this Typescript snippet: let action = function (): void { //perform actions }; let result = action(); What makes it suitable for the TypeScript compiler? ...

Is there a way to upload multiple files using expressjs?

I'm looking for a way to efficiently send multiple files, including an entire directory, so that I can access them in another JavaScript file called from an HTML file. const app = require("express")(); const http = require("http"). ...

What is the proper way to implement a class decorator in TypeScript?

How can a class decorator be implemented to accept only specific classes? A attempted solution is as follows: class Component { age: number; } function registerComponent(name: string) { return <T extends Component>(constructor: T): T => { ...

Discover the steps for generating this graph using ZingChart

I have been experimenting with ZingChart in an attempt to replicate a chart that has the same look and functionality as this example: https://i.stack.imgur.com/PGNK3.png Despite making numerous adjustments to a bar chart, I have not been able to achieve ...

Typescript's spellbinding courses

I'm encountering some issues with Typescript and the "@botstan/Magic" library in nodejs. Before we proceed, please take a look at the "Magic" documentation. Follow these lines: import Magic from "@botstan/magic"; import * as _ from "lodash"; @ ...

Is it possible to use jquery to specifically target classes?

I am trying to achieve the following: $('.class.img').css('cellpadding', variable); However, this code does not seem to be working as expected. Despite searching online, I have not been able to find a solution. Any assistance on how to ...

Error in ReactJS: Trying to access property 'items' of an undefined object

I've been diving into ReactJS, but I've hit a roadblock with this perplexing error. My goal is to update the parent's items array state from its child component. To achieve this, I attempted to pass the addItem function as a prop to the chi ...

Error: Unable to locate attribute 'indexOf' within null object in vuejs when using consecutive v-for directives

I've been struggling with this issue for hours. I'm using vuejs' v-for to render items in <select> element's <options>, but I keep getting a type error. I've tried changing the :key values, but it still won't rende ...

jquery-powered scrollable content container

<script language="javascript"> $(document).ready(function($) { var methods = { init: function(options) { this.children(':first').stop(); this.marquee('play'); }, play: function( ...

I have created an Express.js application. Whenever I visit a page, I consistently need to refresh in order for the variables to appear correctly

Hello, I'm seeking some assistance. Despite my efforts in searching for a solution, I have not been successful in finding one. I've developed an application using Express.js that includes a basic form in jade. The intention is to display "Yes" i ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...