Utilizing async and await in Angular for ensuring a function completes before moving on to the next steps

My challenge involves uploading images before saving a record to a database. I require the upload process to finish completely before the record is saved.

Here is the function responsible for handling image uploads:

  async uploadTrainingModule(selectedFiles: any = this.files) {
    // Image Upload Process
    for (let i = 0; i < selectedFiles.length; i++) {
      await this.filesUploaded.push(selectedFiles[i]);
    }
  }

By utilizing async and await in the above method, my intention was for it to finalize before proceeding with anything else in the subsequent method below (which is responsible for writing to the database):

 createTrainingModule() {
    this.uploadTrainingModule().then(resp => {
        // Database Writing Code Here
    })
  }

I aim to ensure that the code following the comment only runs AFTER the entire uploadTrainingModule method has completed. However, my current implementation does not seem to achieve this. What alternative approach should I consider?

Answer №1

To accomplish this task, utilize the power of RxJS functions through these steps:

  • Aggregate all upload functions into a single Observable using forkJoin and return it from the method uploadTrainingModule.
  • Subscribe to the aforementioned Observable within your createTrainingModule function and execute necessary actions inside the subscribe block.

Your code structure should resemble the following snippet:

import { forkJoin, from, Observable } from "rxjs";

uploadTrainingModule(selectedFiles: any = this.files): Observable<any> {
  // Implement Image Upload
  // `forkJoin` consolidates all inner Observables (created from promises using RxJS's `from` function) into a single Observable once they complete
  return forkJoin(
    selectedFiles.map((file) => from(this.filesUploaded.push(file)))
  );
}

createTrainingModule() {
  this.uploadTrainingModule().subscribe((resp) => {
    // Include DB upload logic here
  });
}

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

What is the reason behind TypeScript indicating that `'string' cannot be assigned to the type 'RequestMode'`?

I'm attempting to utilize the Fetch API in TypeScript, but I keep encountering an issue The error message reads: Type 'string' is not assignable to type 'RequestMode'. Below is the code snippet causing the problem export class ...

Retrieving the value of an object using a key in TypeScript

Is there a way to create an object using keys from another object and determine the type based on a string? For example: const result = rebuild(query, { name: 'string' }); // query - { name: '123', dont_need: true } // result - { n ...

Embedding and authorization

I'm currently working on incorporating the OHIF DICOM viewer into an iFrame within an Angular project. However, it seems that Google accounts are not allowed to function within an iFrame (OAuth is required with the OHIF viewer). Is there a way to enab ...

Variability in determining union types for matched conditional results

In my experience, I have noticed a discrepancy in TypeScript's type inference when dealing with conditional return statements in functions. I have two identical functions, register and register2, outlined below: const register = (step: 1 | 2) => { ...

Is there a method in typescript to guarantee that a function's return type covers all possibilities?

In the case of having a constant enum like: enum Color { RED, GREEN, BLUE, } A common approach is to create a helper function accompanied by a switch statement, as shown below: function assertNever(x: never): never { throw new Error(`Unexpecte ...

Is there an Angular counterpart to Vue's <slot/> feature?

Illustration: Main component: <div> Greetings <slot/>! </div> Subordinate Component: <div> Planet </div> Application component: <Main> <Subordinate/> </Main> Result: Greetings Planet! ...

Difficulty in converting class-based JS useState array to TypeScript Hook

Recently, I've delved into the world of React / TypeScript and have taken on a personal project to enhance my skills. As part of this project, I am in the process of transitioning some class-based code into hooks. Here is the (JS) class-based code th ...

I am struggling to comprehend the data organization illustrated by the typescript type declaration

type DocumentData = { [field: string]: any }; let data1: DocumentData = {4:3}; console.log(data1); //{4:3} It appears that the DocumentData type in the code above defines an object type where the key is of string type and the value can be of any type. Th ...

Issue with Angular 7: In a ReactiveForm, mat-select does not allow setting a default option without using ngModel

I have a Angular 7 app where I am implementing some reactive forms. The initialization of my reactive form looks like this: private initFormConfig() { return this.formBuilder.group({ modeTransfert: [''], modeChiffrement: [' ...

Controlling cell selection in Ag Grid using Angular 2+ to limit multiple selections

Is there a gridConfig option that can prevent multiple cell selection in ag-grid? I would like to avoid selecting multiple cells when using Shift or Ctrl. ...

The value of this.$refs.<refField> in Vue.js with TypeScript is not defined

During the process of converting my VueJs project to TypeScript, I encountered an error related to TypeScript. This issue arises from a component with a custom v-model implementation. In the HTML, there is an input field with a 'plate' ref that ...

Angular does not support the functionality of having multiple material paginations within a single component

I am currently working on creating a component that contains two dataTables, each with a different dataSource. However, I am facing an issue where my Tables are not visible immediately after the component is loaded due to the *ngIf directive being used. Be ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

Implementing canActivate guard across all routes: A step-by-step guide

I currently have an Angular2 active guard in place to handle redirection to the login page if the user is not logged in: import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from ...

Can you explain the key distinctions among Highland.js, Kefir.js, and Rx.js?

Given the emphasis on objective answers on SO, my inquiry is focused on understanding the distinct functional and performance characteristics of these three functional/reactive libraries. This knowledge will guide me in selecting the most suitable option ...

Invoke a function within a component, within that very component

Hey there, I've got an Angular 2 component with a @HostListener. My goal is to call a method from this component using the @HostListener. Check out the code snippet below for my attempt at implementing this: The Component import { Component, Host ...

Expanding MaterialUi styled components by incorporating TableCellProps: A guide

When trying to create a styled TableCell component in a separate file, I encountered an error in TypeScript (ts(2322)). TypeScript was indicating that the properties "component," "scope," and "colSpan" could not be used because they do not exist in StyledC ...

Is there a way to integrate TypeScript with styled components to display suggested properties on the component?

Hey there fellow developers! I'm currently diving into the world of TypeScript and trying to get the hang of it. One thing that's bothering me is not being able to see recommended props on a styled component while using TypeScript. For instance ...

Sending an empty payload in Angular's Http Post request

I am trying to run a simple PHP code that retrieves and prints item names and descriptions from a form submission. Here is the code snippet: echo ($_POST['prod_name']); echo ($_POST['prod_desc']); exit; makeRequest() { ...

What makes Mathematics a unique object in JavaScript programming?

Recently, I've dived into learning Javascript, so pardon me if my doubts seem a bit illogical. I came across the definition for a Math object, and here is the code snippet: interface Math { /** The mathematical constant e. This is Euler's nu ...