TypeScript - patiently anticipating the completion of nested for loops

Currently, I am working on a task that involves implementing two nested for loops in my code. The primary objective of the first loop is to make an API call, which is dependent on the IDs selected by the user. Unfortunately, the limitation of passing only one ID at a time to the API poses a challenge. The nested loop is responsible for processing the data returned by the API and storing it in an array. My ultimate goal is to consolidate all the data into a single array and transfer it to a child component using @Input(). Although I experimented with using a Promise to accomplish this task, there seems to be an issue that needs resolving. Specifically, I want the ngOnChanges() function in the child component to trigger only after the completion of both for loops' execution. Below is the code snippet that outlines my approach:

Parent Component:

  getData() {
    let temp: MyObjectType[] = [];
    let allDataToSend: MyObjectType[] = [];

    return new Promise<MyObjectType[]>((resolve, reject) => {

      for (let i = 0; i < this.userIdSelections.length; i++) {
        this.dataService.getData(this.userIdSelections[i])
          .subscribe(results => temp = results,
            error => {
              this.getRequestResult = <any>error;
            },
            () => {

                for (let j = 0; j < temp.length; j++) {
                  allDataToSend.push({
                    Property1: temp[j].Property1,
                    Property2: temp[j].Property2,
                    Property3: temp[j].Property3,
                    Property4: temp[j].Property4,
                  });
                
              }
            }
          );
      }
      resolve(allDataToSend);
    });
  }

  finalResults() {
    this.getData().then(response => {
      this.FinalObjectSendToChild = response;
    })
  }

Parent Template:

<button mat-flat-button color="primary" (click)="finalResults()">Search</button>

<app-child [finalData]="FinalObjectSendToChild"></app-child>

Child Component:

export class ChildComponent implements OnChanges {
  @Input() finalData: MyObjectType[];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;
  public tableColumns = ['Property1', 'Property2', 'Property3', 'Property4'];
  public tableData: any

  constructor() { }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.finalData) this.createTable();
  }

  createTable() {
    console.log(this.finalData); // displays expected data
    console.log(this.finalData.length); // however, always returns 0
    // the table created is blank...
    this.tableData = new MatTableDataSource(this.finalData);
    this.tableData.sort = this.sort;
    this.tableData.paginator = this.paginator;
  }

Answer №1

If you need to fetch data from multiple sources asynchronously and handle them all at once, consider using Promise.All:

(...)
for (let i = 0; i < this.userIdSelections.length; i++) { 
  arrayPromises.push(this.dataService.getData(this.userIdSelections[i]).toPromise());
}

Promise.all(arrayPromises).then((values) => {
  const allDataToSend = [];
  for(let value of values) {
    for (let j = 0; j < value.length; j++) {
        allDataToSend.push({
          Property1: value[j].Property1,
          Property2: value[j].Property2,
          Property3: value[j].Property3,
          Property4: value[j].Property4,
        });
    }
  }
  resolve(allDataToSend);
});
(...)

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

The Javascript modification of an ASP.NET TextBox goes unnoticed

For someone skilled in this area, this task should be a breeze. I have three components: a launch calendar button, a continue button, and a date textbox. When the button is clicked, a JavaScript calendar pops up in a new window. This calendar sets a date ...

Utilizing TypeScript with Sequelize for the Repository Design Pattern

I am in the process of converting my Express API Template to TypeScript, and I am encountering difficulties with the repositories. In JavaScript, the approach would be like this: export default class BaseRepository { async all() { return th ...

Tips for enhancing the width of the extrude shape in the x and z axes using Three.js

After creating a shape using extrude geometry, I found that I needed to increase the thickness along the x and z axes. Although I used bevelThickness to increase the thickness along the y axis, I still need to adjust it further. For reference, please see ...

Even after assigning the class "img-fluid" to my image, it still fails to properly adjust to the screen size

I added the class "img-fluid" to my image in Bootstrap, but it's not fitting on my webpage. What should I do? <img src="images\406201.jpg" class="img-fluid" alt="..."> <div style="margin-top: 0p ...

Is there a way for me to access the user's gender and birthday following their login using their Google account details?

I have successfully implemented a Google sign-in button in my Angular application following the example provided in Display the Sign In With Google button: <div id="g_id_onload" class="mt-3" data-client_id="XXXXXXXXXXXX-XX ...

Attempting to refresh MongoDB using the Angular framework

I am trying to update an element within an array in a MongoDB Schema using Mongoose for data manipulation. The field in my schema that needs updating currently appears like this: players: [ { type : Schema.ObjectId, ref: 'User' } ], I am wo ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

finding the node version in a code repository

Is it possible to determine the targeted node version (4 or 6) of a Node.js application by examining its code? I'm currently reviewing this: https://github.com/jorditost/node-postgres-restapi ...

Ways to extract information from a dynamically loaded webpage

Is there a way to extract data from a news website that automatically reloads at set time intervals? I want to use this data on my own website as information, whether it's in the form of images or text. Can anyone guide me on how to retrieve data from ...

Is there a way to direct to a particular section of an external website without relying on an id attribute in the anchor tag?

I am aware that you can link to specific id attributes by using the following code: <a href="http://www.external-website.com/page#some-id">Link</a> However, what if the external HTML document does not have any ids to target? It seems odd tha ...

What is the best way to implement a Navbar link in React.js?

I am currently working on developing a website using Reactjs. I have successfully created a Navbar with two links - Home and Contact. However, when I click on the Contact link, although the URL changes accordingly, the page itself does not update. I have s ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

Creating a dynamic sidebar based on roles in AngularJS

I'm looking to create a dynamic sidebar based on the user's role, which is stored in $rootScope.login. However, I'm unsure of how to integrate it into template.js. Below is my JavaScript code and I'm still relatively new to AngularJS. ...

When the next() function of bcrypt.hash() is called, it does not activate the save method in mongoose

Attempting to hash a password using the .pre() hook: import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2" (<any>mongoose).Promise = require('bluebird'); const user_schema = new Schema({ email: { type: String, required: tru ...

Attempting to access an HTTP Node server from within an HTTPS environment resulted in an SSL error

I am faced with the challenge of connecting to a socket.io from a React client within a Node server. Both the React client and the location of the Node server (a microservice housed in a separate Docker container alongside a Java container) are operating o ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

A guide to retrieving JSON data with Javascript

I'm in the process of building a small website for weather forecasting. However, I've encountered an issue when trying to retrieve JSON data from accuWeather - I'm not getting any response. I've double-checked my request and it seems to ...

"Integrating Associated Models with Sequelize: A Step-by-Step Guide

I am attempting to retrieve all transactions along with their associated stripePayments, but I keep encountering the error include.model.getTableName is not a function. In my database schema, there is a table for transactions that has a one-to-many relati ...

The TypeScript 'object' type

My query regarding the definition of TypeScript's {} type has brought about some confusion. Initially, I believed it represented an "empty object with no properties," but I recently encountered an ESLint rule that prohibits the use of {} type because ...

Master the art of properly switching on reducer-style payloads in Typescript

Currently, I am dealing with two types of data: GenArtWorkerMsg and VehicleWorkerMsg. Despite having a unique type property on the payload, my Searcher is unable to differentiate between these data-sets when passed in. How can I make it understand and dis ...