Ensure to provide a promise within the forEach loop

How do I go about returning a promise in the deleteBudgets() method below so that I can use await inside the updateBudgets() method?

deleteBudgets

  deleteBudgets(data: Budget[], projectId: string): Promise<void> {
    forEach(data, (d: Budget) => {
      this.fireStore.doc(`projects/${projectId}/budgets/${d.id}`).delete();//here it returns Promise<void>
    });
  }

updateBudgets

 updateBudgets(data: Budget[], projectId: string): Budget[] {
    await this.deleteBudgets();//here  

    let budgets: Budget[] = [];
    forEach(data, (d) => {
      const budgetId: string = this.fireStore.createId();
      d.id = budgetId;
      budgets.push(d);
      this.fireStore.doc<Budget>(`projects/${projectId}/budgets/${budgetId}`).set({
        id: budgetId,
        amount: d.amount,
        contingency: d.contingency,
        budgetGroup: d.budgetGroup,
        creationTime: moment().format()
      })
    })
    return budgets;
  }

Answer №1

Generate an array filled with promises:

removeBudgets(data: Budget[], projectId: string): Promise<void> {
  data.map((d: Budget) => this.fireStore.doc(`projects/${projectId}/budgets/${d.id}`).delete());
}

Next, utilize promise.all to ensure all promises are resolved:

removeBudgets(data: Budget[], projectId: string): Promise<void[]> {
  return Promise.all(data.map((d: Budget) => this.fireStore.doc(`projects/${projectId}/budgets/${d.id}`).delete()));
}

Detailed information on promise.all

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

Executing test units in Angular

While setting up unit tests for my Angular app, I expect the ngInit function to be called. Component.ts: ngOnInit() { this.topToolBarService.change.subscribe(customer => { this.filter.customerid = customer; this.customerid = customer; ...

Tips for utilizing string interpolation in the style tag of an Angular component

@Component({ selector: 'app-style', template: ` <style> .test { color: {{ textColor }} } </style> ` }) export class StyleComponent { textColor = "red"; } The current method doesn't appear to b ...

Transforming API data into a particular type using Typescript

I am looking to extract only specific properties from a given object. Can TypeScript interfaces be used to iterate through the data and eliminate unnecessary properties? Sample data: [ 0: { "original_language" : "en", "t ...

The shared service is malfunctioning and displaying inconsistent behavior

app.component.ts import { Component } from '@angular/core'; import { HeroService } from './hero.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.compon ...

Positioning customized data on the doughnut chart within chart.js

Is there a way to customize the position of the data displayed in a doughnut chart? Currently, the default setting is that the first item in the data array is placed at 0 degrees. However, I need to place it at a custom position because I am working on a ...

Struggling to vertically center ion-search bar within Ionic header section

I'm really struggling to center an ion-searchbar within my navigation bar. I've experimented with text-align and ion-grids, but nothing seems to be effective. It has to be the component itself. https://i.sstatic.net/OWDPZ.png index.html <io ...

Struggling with sluggish performance on a certain project within VS Code

My experience with VS code has been excellent over the years, but I recently encountered a problem in one of my projects that caused a significant slowdown in performance. Strangely, other projects are working fine without any issues on VS code. I suspect ...

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

Tips for preventing duplicate data fetching in Next.js version 13

I am currently in need of retrieving information from the database, generating metadata, and displaying the page content. The current method I am using is as follows: export const generateMetadata = async ({ params: { questionSlug }, }: Props): Promise&l ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

Enabling local host API requests while maintaining Content-Security-Policy restrictions

My recent exploration led me to electron, which I utilized to develop a Windows app for my ionic-angular web application. I am eager to make API calls to a localhost API. Up until now, I have resorted to simply deleting the Content Security Policy using ...

The parameter 'Node' cannot be assigned to the type 'CustomElement'. Error code: ts(2345)

Currently, I am developing a collaborative real-time text block editor using liveblocks technology. I have encountered some errors in my Editor.tsx file while working in VSCode. Could you provide some suggestions on how to resolve this issue? Error: Ar ...

Angular 13 implementation of a double-loop structure for fetching data from an API

I'm facing an issue with retrieving specific data fields label and svm from a JSON file. The desired fields are nested inside PORTFOLIO > REGROUPEMENT > ELEMENT. You can access the JSON file here. img(1) I've attempted to display the dat ...

Converting ASP .Net Core Dto's and Controllers into TypeScript classes and interfaces

My concept involves incorporating two key elements: Converting C# Dto's (Data-transfer-objects) into TypeScript interfaces to ensure synchronization between client-side models and server-side. Transforming ASP .Net Core controller endpoints into Typ ...

The parameter type 'DateInput' cannot be assigned to the parameter type 'Date'

I am currently utilizing fullcalendar for my project. However, I would like to utilize my local models instead of fullcalendar's model. The issue arises when attempting to create a new instance of my own model, as it displays the following error messa ...

Setting up a .NetCore3.1 API on LinuxCentos with Nginx

Currently, I am facing an issue while attempting to deploy a .NET Core 3.1 API + Angular application on Linux Centos. The application runs fine on the server; however, the browser fails to load it properly. Surprisingly, when I publish the same project for ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...

Exploring the power of flow.js within an Angular 2 Typescript project

I am trying to incorporate flowjs or ng-flow into my Angular 2 application. After installing the flowjs typings using npm install --save-dev @types/flowjs from However, upon importing it into my component with import { Flow } from 'flowjs';, ...

How can I merge two slightly shifted videos in React to produce a stereoscopic 3D video?

I have two videos that were recorded simultaneously with a slight horizontal offset. I want to combine them to create a 3D video that can be viewed using 3D glasses (not the red/blue ones). Can this be done in React + TypeScript? I've heard that it&a ...

Issues with Angular routing in Fuse administrator and user interfaces

I am encountering an issue with navigating routes for admin and user roles, where the user role has limitations compared to the admin role. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.1/angular.min.js"></script> const ...