Iteration in Angular using ForEach Statement

Can anyone help me with executing a For loop synchronously in Angular 5? The code I have so far doesn't wait until ExcecuteAsyncCode is completed.

let items = new Array<Item>();

for (let i = 0; i <= 10000; i += 1) {

    this.ExcecuteAsyncCode(i).then(
    res => {
        let result = res;
        return result;
    }).then(response => {
        let temp = response as Item[];
        temp.forEach((cta: Item) => {   
          items.push(cta);
        });
    });

    // THIS EXCECUTED BEFORE ExcecuteAsyncCode PROMISE COMPLETED
    if (items.length < i) {
        return;
    }
}

Answer №1

Waiting synchronously for an async operation to complete is not possible, and even if it were possible, it would not be recommended as it could potentially block the browser UI.

To handle asynchronous operations, you can either chain together then calls or utilize async /await for a more synchronous-looking code structure.

interface Item{
    id:number
}
class Test{
    async ExecuteAsyncCode(i:number) {
        return [] as Item[]
    }
    async method() {
        let items = new Array<Item>();

        for (let i = 0; i <= 10000; i += 1) {

            let temp = await this.ExecuteAsyncCode(i);
            temp.forEach((cta: Item) => {
                items.push(cta);
            });

            if (items.length < i) {
                return;
            }

        }
    }
}

If you want to learn more about async /await, you can visit this resource. It's important to note that async await is not limited to Typescript, but it's also being implemented in Javascript.

Answer №2

UPDATE: It's important to note that mixing synchronous (for-loop) and asynchronous code can lead to complications. The following approach removes the for-loop but still accomplishes the intended goal based on your query.

export class AppComponent {

  ngOnInit() {
    this.executeMethod();
  }

  counter: number = 0;

  // Suppose the async process will stop once the counter reaches 5
  items = 5; 

  executeMethod() {
    this.asyncProcess().then((result) => {
      if (this.counter > 10) return;

      if (result === 'exit') { 
        return;
      }
      else {
        this.counter += 1;
        this.executeMethod(); 
      }
    });
  }

  asyncProcess() {
    return new Promise((resolve) => {
      let currentAsyncTask = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 3000);
      }).then(() => {
        if (this.items < this.counter) {
          resolve('exit');
        } else {
          resolve('done');
        }
      });
    });
  }
}

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 merge various input values

I need help combining input values in my code. Below is the code I have so far: getCodeBoxElement(index) { return document.getElementById("codeBox" + index); } onKeyUpEvent(index, event) { const eventCode = event.which || event.keyCode; console.lo ...

Utilize rxjs to effectively handle API data responses and efficiently manage the state of your application within Angular 10

I'm currently exploring the most efficient method for storing and updating data from an API, as well as sharing that data among sibling components. Here's my initial attempt: Storing the Observable export class MyExampleService { private data ...

Troubleshooting Office-Js Add-ins using Angular-CLI and F12chooser: Map files not visible

When I first started developing Office Add-ins, I was using Angular with Webpack. Now, however, I am eager to try it out with Angular-CLI. Everything seems to be working fine, except for one thing: F12Chooser Debugging Previously, I was able to debug my ...

What methods are most effective for integrating a Loading indicator into a redux-saga application?

Currently, my app is being developed using a combination of redux, redux-saga, typescript, typesafe-actions, and ducks. I am exploring different ways to incorporate a loading indicator while making API calls. This is the structure I have in place: sta ...

Exploring the Functionality of PeerJS and Angular4: Controlling Camera and Microphone Access During Streaming

Currently, I am developing an Angular4 app that includes a video call module. The two modules I have created - host and client - are successfully enabling video calls between them. Now, I need to add two buttons for turning the camera and microphone on and ...

Ways to turn off automatic opening of Google login prompt

I have integrated the abacritt/angularx-social-login package into my project. After injecting SocialAuthService into my constructor, Google signup functionality is automatically displayed on the frontend. Is there a way to prevent this behavior and inste ...

Execute Angular within a designated directory

Can Angular be launched in a custom URL path like http://localhost:4200/abcde instead of just http://localhost:4200/? I have been unable to find any settings for changing the pathname. ...

How can I display an agm-polyline within a map in Angular 7?

I need assistance with adjusting the polylines on my map and dynamically setting the zoom level based on their size and position. Here is the code I am currently using: <agm-map style="height: 500px" [latitude]='selectedLatitude' [longitude ...

Exploring Generics and Type Inference within TypeScript

(In reference to this question) I've developed a function that takes in a configuration object containing state definitions, essentially creating a state machine. For example: const machine = createStateMachine({ initial: 'inactive', s ...

Steps for transforming a .Net Core 2.2 / Angular 8 application into a Progressive Web App

I am currently facing challenges in converting a .NET Core 2.2 / Angular 8 app from the Visual Studio Angular SPA Template into a Progressive Web App (PWA). Despite following Angular documentation for creating and testing a basic Angular PWA, I have not be ...

What is the process for running an npm package command on a specific subdirectory using PowerShell?

Is there a way to run an npm package command on a specific subdirectory using PowerShell? My situation involves having an ng2 application embedded within a .NET MVC app. The ng2 directory is nested within the main root directory structured as MySite/ng2. ...

Incorporating parent ID data into hierarchical property structures

I am looking to extract the ID values from the previous object and construct an array of IDs within each parent item. The process must be generic and should not rely on the property names. However, all properties inherit a base class called SubResource. On ...

What is the process of mapping an object from a JSON file to a different object?

Displayed below is my json file { "data": [ { "firstName": "Tom", "lastName": "Yoda", "type": "guest", "id": "0", "gender&quo ...

Dealing with a 404 Error in Instagram API Using RXJS

Utilizing the Instagram API without OAuth involves using this URL: https://www.instagram.com/explore/tags/{tag}?__a=1 Everything works smoothly, I successfully obtain and manipulate the JSON data. However, when a non-existing tag is used, I encounter a 40 ...

Using Angular 2+, learn how to effectively utilize and monitor the output emitter when utilizing the createComponent factory method

When I dynamically create a component in ParentComp, the code looks like this: const factory = this.resolver.resolveComponentFactory<ChildComp>(component); this.componentRef = this.container.createComponent(factory); this.componentRef.instance.dataC ...

The type 'HTMLDivElement | null' cannot be assigned to the type 'HTMLDivElement' in this context

Struggling with a scroll function to maintain position while scrolling up or down - encountering an error: Error: Type 'HTMLDivElement | null' is not assignable to type 'HTMLDivElement'. Type 'null' is not assignable to type & ...

rxjs module is mysteriously missing in Visual Studio 2019, yet it can be easily located when using the t

I recently integrated TypeScript into an aging angularjs project with the intent of eventually transitioning to Angular 2+. In my TypeScript code, I am eager to utilize rxjs observables; however, I have encountered some unexpected behavior during my attemp ...

Enumerated Types in Typescript

Although this question has been asked multiple times, I am still struggling to grasp the concept of enums. Let's consider a simple enum: export enum Type { Null, First, Second, Third } Now, the query is, what is the difference between th ...

Managing Deactivated Elements in Ionic Web Edition

In my extensive ionic application that I deploy to both the Web and mobile platforms, a member of the testing team brought to my attention an issue regarding disabled elements. I have numerous elements such as buttons, checkboxes, inputs, etc., which can b ...

How to retrieve the current validators for a form control in Angular 2

In this scenario last_name = new FormControl('', [Validators.required, Validators.minLength(2)]); Depending on the circumstances, I might add or remove validators for the last name control. Ultimately, how can I determine which validators are ...