Typescript's async function failing to execute properly

I'm currently facing an issue with my code and I'm a bit puzzled as to where the problem lies. The console is displaying the correct data for this.allNominations, but it appears that the third for-loop is not being executed at all. As a result, the values in nominationDepartmentMap are not being populated. I understand that my question may lack clarity, but any assistance would be greatly appreciated!

async getAllNominations() {
    this.loadingAllNominations = true;

    for (let nominee of this.allNominees) {
      this.apiService.getNominations(nominee.email).subscribe((data) => {
        this.allNominations.push(...data);
      });
    }

    console.log( this.allNominations);

    let nominationDepartmentMap = new Map<number, Nomination[]>();
    for (let department of this.departments) {
      nominationDepartmentMap.set(department.id, []);
    }

    for (let nomination of this.allNominations) {
      console.log('hello')
      for (let department of this.departments) {
        if (nomination.nominee.departmentId == department.id) {
          if (!nominationDepartmentMap.has(department.id)) {
            nominationDepartmentMap.set(department.id, []);
          }
          nominationDepartmentMap.get(department.id)!.push(nomination);
          break;
        }
      }
    }

    console.log(nominationDepartmentMap);
}

Link to screenshot of console logs

Answer №1

If you're waiting for the observables in the first for loop, you can experiment with this approach:

async retrieveAllNominations() {
        this.loadingAllNominations = true;

for (let nominee of this.allNominees) {
  this.allNominations.push(await this.apiService.getNominations(nominee.email).toPromise());
}

console.log( this.allNominations);

let nominationDepartmentMap = new Map<number, Nomination[]>();
for (let department of this.departments) {
  nominationDepartmentMap.set(department.id, []);
}

for (let nomination of this.allNominations) {
  console.log('hello')
  for (let department of this.departments) {
    if (nomination.nominee.departmentId == department.id) {
      if (!nominationDepartmentMap.has(department.id)) {
        nominationDepartmentMap.set(department.id, []);
      }
      nominationDepartmentMap.get(department.id)!.push(nomination);
      break;
    }
  }
}

console.log(nominationDepartmentMap);
}

Alternatively, you can also consider using the forkJoin operator to synchronize and wait for all observables.

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

When a user clicks on the download link, it redirects them to the homepage in Angular

When using Angular 6 and the downloadFile method to download an Excel sheet from the WebAPI, everything runs smoothly. A dialog box opens up asking to save the file on the drive, but then it unexpectedly navigates me back to the home page. This redirects ...

Trapped in a never-ending cycle caused by failing to dispatch an action within ngrx/effects

My current setup involves using Angular2, ngrx/store, and ngrx/effects for state management. I have encountered an issue where I am unable to display an error message when a specific action fails within an @Effects() block. Here is the problematic code sn ...

Leverage Springs with TypeScript

function createDefaultOrder(items: any[]): number[] { return items.map((_, index) => index); } type CustomHandler<T> = (index: number) => T; type CustomValues = { zIndex: number, y: number, scale: number, shadow: number, immediate: ...

The 'xxx' type does not have an index signature, so the element is implicitly assigned an 'any' type

I'm currently facing an issue with TypeScript. The error message I'm encountering is related to the following section of code: The Interface: export default interface IUser { username: string; email?: string; isActive: boolean; group: s ...

The parameter cannot be assigned the readonly type 'X' in this context

I encountered an issue with a third-party library where the class structure changed. Initially, it was defined as: export class Foo { field: X[]; …. } In my code, I was working with this type: print(foo.field) After updating to a new version, the c ...

Listening for events from an Angular 4 component within an AngularJS controller

Currently, I am in the process of developing a hybrid angular application. One specific requirement I have is to monitor an event (potentially an observable) within the angularjs controller that would be initiated by an angular 4 component. Are there any ...

Guide to encapsulating an asynchronous function in a promise

I am in need of wrapping an asynchronous function within a promise to ensure synchronous execution. The reason behind this is that I must obtain a result from the asynchronous function before proceeding with the program's execution. Below is the rele ...

Leverage angular to dynamically update excel sheet with parsed data

Question: I am currently trying to pull data from a website using Angular and I would like to export this data into an Excel file. Additionally, I want the ability to update this file with more data in the future. Is there a library that can help achieve ...

Angular 2, using Jasmine and Karma for testing, encountered an error with the HTTP testing API, which returned an error message stating: {"isTr

I've set up an http test case for my Angular2 app using Jasmine-Karma and encountered an API error: Uncaught API Error. Scenario: I'm trying to test an http service for my Angular2 App using Karma-Jasmine, and I've implemented the method be ...

Display or conceal an icon based on the data in the field

Can someone provide guidance on how to make an icon appear or disappear based on the logic within [ngIf]? The icon should only be displayed if there is information in a specific field. Should I implement this inside ngIF or in my TS file? Can the icon cl ...

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

What is the method for including a TabIndex property in a JSON file?

I discussed the integration of HTML fields within a JSON file and highlighted how to utilize the TabIndex property effectively in JSON files. ...

Having trouble sending data with a POST request using Angular 4's HttpClient?

Angular 4.4.4 This is an introduction to my app component constructor( private http: HttpClient, ) this.http.post('/api.php', {name, age}).subscribe(response => { console.log(response); }); api.php -> exit(json_encode($_P ...

Removing duplicate elements from an array in TypeScript

In my TypeScript code, I am working with an array of objects and need to remove any duplicates. The code below accomplishes this task: const uniqueObjects = Array.from(new Set(nonUniqueObjects.map((x) => { return JSON.stringify(x); }))). ...

Pause for Progress - Angular 6

I'm looking for a solution to solve the following issue. I need to access a property that will store data from an http request. Therefore, I want to verify this property only after the transaction is completed. validateAuthorization(path: string): ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

Automatic renewal of bearer token in Angular 7

My AuthService has two key methods: getAuthToken (returns a Promise to allow lazy invocation or multiple invocations with blocking wait on a single set) refreshToken (also returns a Promise, using the refresh token from the original JWT to request a ...

Setting the base path for npm tests: A step-by-step guide

I am currently working on a web application that utilizes Angular as the front-end technology and Java Spring Boot as the backend. https://i.sstatic.net/IWPNZ.png In the screenshot above, you can see that I have created a new directory within the root fo ...

Stay Alert: Angular Observable Continuously Monitored for Promise Updates

I am currently working on an angular application that has a connection with a printer. The printer possesses its own status service that is implemented as a promise, providing the printer's current status as a response. However, I am facing an issue w ...

Yarn Plug'n'Play was unable to locate the module during the next build

Currently, I am in the process of developing a Next.js project with yarn's Plug'n'Play feature. In this project, I have created several pages and added various packages, including mathjs: '^10.3.0' to assist me in parsing user inpu ...