Hold off until all commitments are fulfilled in Firestore

Is there a way to ensure that all promises are resolved before moving on to the next line of code? Currently, it seems like it's moving to the next line without completing the operation below. I want to make sure that the forEach loop is fully executed before proceeding to the next step. How can I achieve this?

forEach(project.projectDetail.memberList, async (m) => {
        const memberDocumentRef: firebase.firestore.DocumentReference = this.fireStore.doc(`members/${m.id}`).ref;
        await this.fireStore.firestore.runTransaction(transaction => {
          return transaction.get(memberDocumentRef).then(memberDoc => {
            let currentProjects: Project[] = memberDoc.data().projects;
            const finalProjects = filter(currentProjects, (p: Project) => { return p.id != project.projectDetail.id; });//projects Without Updated Project
            finalProjects.push(project.projectDetail);
            transaction.update(memberDocumentRef, { projects: Object.assign({}, finalProjects) });//update projects on each member
          });
        });
      });

Answer №1

To optimize this code, consider utilizing Promise.all in conjunction with switching the forEach loop to a map:

// By using Promise.all, a promise is returned that resolves once all inner promises are complete.
// You can then choose to handle dependent code within its .then method or await it:

await Promise.all(project.projectDetail.memberList.map(async (m: Member) => {
    const memberDocumentRef: firebase.firestore.DocumentReference = this.fireStore.doc(`members/${m.id}`).ref;
    await this.fireStore.firestore.runTransaction(transaction => {
        return transaction.get(memberDocumentRef).then(memberDoc => {
            let currentProjects: Project[] = memberDoc.data().projects;
            const finalProjects = filter(currentProjects, (p: Project) => { return p.id != project.projectDetail.id; }); // Updated project without certain ID
            finalProjects.push(project.projectDetail);
            transaction.update(memberDocumentRef, { projects: Object.assign({}, finalProjects) }); // Update projects for each member
        });
    });
}));

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

Can you provide instructions on how to display data in two lines within a mat-select field?

Is it possible to show selected options in mat-select with long strings in two lines within the same dropdown? Currently, the string appears incomplete. You can see an example of this issue here: incomplete string example <mat-form-field class="f ...

Software designed for the web that utilizes both frontend and backend technologies, including JavaScript

Currently, I am collaborating on a project for a company that created software using Delphi. The software primarily featured a minimalist browser as its central component. This browser was used to analyze webpages, recognize patterns, save data, and more. ...

Troubleshooting ion-radio loop error in Ionic 2

I am encountering an issue with the ion-radio component in Ionic 2. The problem is that when the component retrieves data from a service using HTTP and assigns it to the data property within the ngOnInit lifecycle hook, the radio buttons are not able to b ...

What steps can be taken to resolve the issue "AG Grid: Grid creation unsuccessful"?

For my project, I decided to use the modular import approach for AG-Grid. This means importing only the necessary modules instead of the entire package: "@ag-grid-community/core": "31.3.2", "@ag-grid-community/react": ...

Modifying the response header in a node.js middleware: A step-by-step guide

I've been researching this question extensively on Google, but unfortunately, none of the solutions seem to work for me. The issue I'm facing is related to adding a specific property to the response header called "isAuth," which needs to be set ...

Input the variant number TypeScript as the key value pair

I'm struggling to input an abi key "5777" in Typescript. When I receive a network ID and try to set it in the networks key, the linter displays an error. My issue is that I need to specify "networkId" and it's not always a fixed value like "5777 ...

Steps to implement two-way binding in mat-select feature

Here is the code snippet I am working with: <mat-form-field> <mat-select [(ngModel)]="valueFromDB.name"> <mat-option>None</mat-option> <mat-option *ngFor="let option of options" [value]="option. ...

Please refresh the page to view the updated component

Within my Angular 7 application, I have various components that retrieve data from an API by making a call in the ngOnInit function. So far, the CRUD operations are functioning correctly and I am able to obtain the desired results. However, the main issue ...

The ngModel in AngularJS 2 fails to update when the Jquery Date Picker date is changed

Having an issue with the Jquery UI datepicker within an angularjs 2 component. The datepicker is displaying the changed date, but it's not updating the underlying ngModel: dateSelected. dateSelected: string = ''; The date picker input fie ...

The message I received from my Angular 7 application is indicating that 'The specified selector does not correspond to any elements in the document.'

Using Angular 7 and I've implemented a custom component located at src/app/organization/organization.component.ts import { Component, OnInit } from '@angular/core'; import {FormGroup, FormBuilder, Validators} from "@angular/forms"; @Compo ...

Mistakes in combining Angular NgRx actions and union types

After reviewing my code, I have encountered the following issues: In my shared.actions.ts file: import { Action } from '@ngrx/store'; import { Error } from '../error.interface'; export const types = { IS_LOADING: '[SHARED] IS_L ...

TypeScript integrated Cypress code coverage plugin

I've been attempting to integrate the @cypress/code-coverage plugin with TypeScript in my project, but so far I haven't had any success. Here is a breakdown of the steps I've taken thus far: Followed all the instructions outlined in https:/ ...

Instructions for creating a function that can receive an array of objects containing a particular data type for the value associated with the key K

Seeking guidance on how to define a specific signature for a function that accepts an array of objects and 3 column names as input: function customFunction<T, K extends keyof T>( dataset: T[], propertyOne: K, propertyTwo: K, propertyThird: K ...

Is ngClass failing to activate a class upon clicking?

I am having trouble displaying the activated class as active. It briefly switches to that class and then reverts back. Here is what I have tried: <ion-row > <ion-col col-3 (click)="deviceType('Light')" ><div class="c ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...

The incorrect argument is being used to infer the generic type

I have implemented the NoInfer feature from the library called ts-toolbelt. However, it seems that the example provided below does not reflect its intended effect. In this scenario, the generic type is deduced from the util function as soon as it is intr ...

Asynchronously download static images with the power of NextJS and TypeScript integration

I have a query regarding my website development using NextJS and TypeScript. The site features a showcase gallery and is completely static. Currently, the initial view shows thumbnails of images. When clicking on a thumbnail, the original image is display ...

Enhancing the Angular Community Library Project

I am currently working on an Angular project version 7.1 and have developed 2 angular libraries that are being used in the project. In order to upgrade my project from version 7.1 to 8.2, I used the following command: ng update @angular/cli@8 @angular/core ...

Return the subclass from the constructor function

class X{ constructor(input: string) { // do things } f() {console.log("X")} } class Y extends X{ constructor(input: string) { // do things } f() {console.log("Y")} } class Z extends X{ con ...

Utilize the class or interface method's data type

In the context of a child component calling a callback provided by its parent, this situation is commonly seen in AngularJS. As I am utilizing TypeScript, I aim to implement strong typing for the callback in the child component. Here is the initial stat ...