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

Struggling to grasp how to implement Redux and React-router together in one component

I have recently embarked on learning TypeScript and encountered a confusing behavior. Upon encountering this error: Type 'ComponentClass<{}>' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> ...

What is the proper way to utilize queries in BlitzJS?

I am attempting to extract data from a table by filtering based on the relationship with the Blitzjs framework. However, I am facing difficulties using queries as it seems to be the only option available. Every time I try to call the quer ...

Steps to prevent subfolder imports in my npm package

My npm package is built using: typescript webpack webpack.config: {... entry: './src/index.ts } library tree: - package.json - src - - index.ts - - ...all_my_code... I have all my library functionality and types exported from the index.ts file. T ...

Dockerized Nginx: Struggling with location configuration issues

Here is the docker file: FROM nginx:1.17.4-alpine # copy artifact build from the 'build environment' COPY ./dist /usr/share/nginx/html/ COPY ./default.conf /etc/nginx/conf.d/ # expose port 80 EXPOSE 80 # run nginx CMD ["nginx", "-g", "daemon o ...

Which release of "ngx-bootstrap" is compatible with "Angular 17"?

Here's the scoop I attempted to download ngx-bootstarp but couldn't find a suitable version. I searched online, but there was no information available. Checking the list on the Angular Bootstrap official website, I noticed that version 17.0.0 ha ...

Angular 7 is throwing an error because it is expecting the "path" argument to be a string, but it is receiving an object instead

Whenever I attempt to run tests on my Angular project by typing: ng test --browsers=PhantomJS I discovered that I needed to manually install phantomjs using the following command: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

How can one execute a function within an HTML attribute value using Angular?

I am currently attempting to use the weatherToFontAwesomeIcon(weatherDescription: string) function directly within the HTML file for this component. My goal is to showcase a specific FontAwesome icon based on the weather response from the API. import { Cur ...

Ignore one specific file when importing all files in Angular 7

In my Angular 7 project, I am utilizing C3 and importing all the necessary files at the beginning of my .ts component file using a wildcard. import * as c3 from 'c3'; While this method works well overall, I encountered an issue where my CSS ove ...

Custom options titled MUI Palette - The property 'primary' is not found in the 'TypeBackground' type

I am currently working on expanding the MUI palette to include my own custom properties. Here is the code I have been using: declare module '@mui/material/styles' { interface Palette { border: Palette['primary'] background: Pa ...

What are the steps for implementing the ReactElement type?

After researching the combination of Typescript with React, I stumbled upon the type "ReactElement" and its definition is as follows: interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor< ...

Having trouble rendering a Twitter timeline on an Angular 7 project

I am attempting to embed a Twitter timeline in an Angular page by following the instructions outlined at . However, I am encountering an issue where only the button renders and not the actual timeline itself. The code in my index.html file is as follows: ...

Can Next.js accommodate server-side redirection with internationalization?

I'm working on a small Next.js app that has pages accessible only to logged in users. To manage the authenticated routes, I created an HOC (withAuth) that handles redirection on the server side to prevent page flashing on the client side. Everything i ...

Merge three asynchronous tasks into a single observable stream

I have 3 different observables that I am using to filter the HTML content. Here is the TypeScript code snippet: fiscalYear$ = this.store$.select(this.tableStoreService.getFiscalYear); isLoading$ = this.store$.select(this.tableStoreService.tableSelector ...

Using Angular to sort arrays based on the values in a separate array

I have a unique setup where there is a table containing select options in each row. The value of the select option changes based on the 'dataType' specified for that particular row. Here is an example of my Table Array: { 'name':' ...

Angular 5 Dilemma: Exporting UI Components without Locating Template

My current project involves developing UI Components that will be used in various web projects within the company. Our plan is to publish these UI components as an npm package on our local repository, and so far, the publishing process has been successful. ...

Leveraging npm for the development of my TypeScript/Node.js project

I'm facing challenges working on a project written in TypeScript and running on Node. I am finding it difficult to write the npm script to get it up and running properly for development purposes. What I am attempting to achieve is: clear the /dist f ...

Using TypeORM: Implementing a @JoinTable with three columns

Seeking assistance with TypeORM and the @JoinTable and @RelationId Decorators. Any help answering my question, providing a hint, or ideally solving my issue would be greatly appreciated. I am utilizing NestJS with TypeORM to create a private API for shari ...

Changing a particular field value within an array of objects in Angular 4

I have a scenario where I created a class called security: class security { public id:number; public name:string; } Next, I initialized an array of security objects: let s:security[]=[{id:1,name:'Alex'},{id:2,name:'John'},{id:3,nam ...

Implementing TypeScript for augmented styling properties in a component - a guide

I have custom components defined as follows: import React from 'react'; import styled from '../../styled-components'; const StyledInput = styled.input` display: block; padding: 5px 10px; width: 50%; border: none; b ...

Issue with file upload controller in .net core 2.2 and Angular 7: IFormFile always returns null

Despite thorough research and checking other answers, my controller is not receiving any data. Correct API URIs are used and the request does reach the appropriate controller. Unique Angular Snippet: In the component.html file - input field setup <d ...