Sending returned values from a promise to the calling function in Angular

I have a created a promise to retrieve values from a service and then assign them to variables trans and confidence, which should be used as transcript and conf in the save_data function. How can I return these values to the calling function and ensure that no other part of the code executes until the promise is successfully resolved?

 fetchTransValues() {
      return new Promise((resolve, reject) => {
        setTimeout(function() {
            var trans =  this.service.getTranscriptValue();
          var confidence =this.service.getConfidenceValue();
        }, 1000);
      });
    }
    async save_recording(){  

      this.fetchTransValues().then(function(message) {
        this.answer_loading=true;
        let formData=new FormData();
        const transcript_arr = [];
        const confidence_arr = [];

        
        ....
        ....
        this.http.post(this.baseUrl+'api/auth/get-results', formData).subscribe(response  => {
      
      
        });
      });
     

https://i.stack.imgur.com/AKdIp.png

Value inside promise: https://i.stack.imgur.com/aYJ7O.png Any solution to resolve this issue, Thanks

Answer №1

When your promise is resolved, make sure to handle the results from trans and confidence using async and await. This approach also addresses the issue related to this in your code:

class Container {
    service = {
        getTranscriptValue() { return "dummy" },
        getConfidenceValue() { return "another dummy" }
    }
    
    fetchTransValues() {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                const trans = this.service.getTranscriptValue();
                const confidence = this.service.getConfidenceValue();
                resolve({trans, confidence});
            }, 1000);
        });
    }

    async save_recording(){  
        const {trans, confidence} = await this.fetchTransValues();
        console.log("received", trans, "and", confidence);
        this.answer_loading = true;
        // ..etc
    }
};

new Container().save_recording();

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

Update the image on a webpage by simply clicking on the current image

Hey there, I'm looking to implement a feature where users can choose an image by clicking on the current image itself. Here's my code snippet. The variable url holds the default image. My goal is to make the current image clickable so that when ...

Having difficulty updating an angular variable within a callback function

Currently, I am utilizing the Google Maps directions service to determine the estimated travel time. this.mapsAPILoader.load().then(() => { const p1 = new google.maps.LatLng(50.926217, 5.342043); const p2 = new google.maps.LatLng(50.940525, 5.35362 ...

Tips for utilizing PINO to write logs to both file and console

I have successfully implemented logging to a log file using Pino. However, I am wondering if there is a way to also log to the console in order to manage the frequency of 'console.log()' calls. Node Version : 21.6.1 Typescript Version : 5.3.3 Pi ...

Is there a way to reset the selected value of a specific option in Mat-Select?

Using mat-select, I need to reset the selection for a specific value of mat-select's mat-option. For instance, take a look at this example on StackBlitz In the example, the mat-select has three options; when selecting Canada, it should revert back t ...

The rendering process in ag-grid is resulting in the service component initialized from an event to become null

Currently, I am utilizing ag-grid and need help understanding a specific issue. In my method for preparing GridOptions, I have set up an onCellValueChanged event that triggers a service component to access the database and populate the data. However, when ...

Directive for creating a custom loading indicator in Angular

I have created a custom Angular element directive that displays and hides a loading indicator based on a condition from a service call. The directive is used as an element within another element. While the directive itself works correctly, the issue is tha ...

Is there a way to verify if a value is undefined before including it as an object field?

I'm currently working on an Angular project and I have a query regarding TypeScript. It's about correctly handling the scenario where a field should not be included in an object if its value is undefined. In my code, I am initializing an object ...

Angular 4/2: Exploring the Concept of Method Overloading

Currently, I am working on Angular 4 and have been struggling to find a suitable solution for method overloading in Angular 2 or 4. Can we actually implement method overloading in an Angular service class? I would really appreciate if someone could provide ...

The 'jsx' property in tsconfig.json being overridden by Next.js and TypeScript

Is there a way to prevent NextJS from changing the 'jsx' property in my tsconfig.json file from 'react' to 'preserve' when running the development server? This is how my tsconfig.json file looks: "compilerOptions": { " ...

Create an interface that inherits from a class

I am currently in the process of converting some code that attempts to create an instance of http.ServerResponse. However, typescript is throwing an error: [ts] Property 'ServerResponse' does not exist on type 'typeof "http"'. I hav ...

Utilizing npm link with a TypeScript-written module: a guide for seamless development?

I am currently in the process of developing a TypeScript and Webpack-based library. To facilitate the development of this library, I have set up a separate test project (written in JS) and connected the library using npm link <package-name>. Howeve ...

Vue's computed property utilizing typed variables

I am trying to create a computed array of type Todo[], but I keep encountering this specific error: No overload matches this call. Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<T ...

Unable to run TypeScript on Ubuntu due to compilation errors

throw new TSError(formatDiagnostics(diagnosticList, cwd, ts, lineOffset)) ^ TSError: ⨯ Unable to compile TypeScript Cannot find type definition file for 'jasmine'. (2688) Cannot find type definition file for 'node'. (2688) api/ ...

Tips for including new items in an array within a subscribe valueChanges in Angular

What is the process for extracting values from a reactive form and storing them in an array when the form is valid? My application features dynamic forms with various fields that appear dynamically. retrieveFormValues(){ let valuesArray = []; this.fo ...

An issue has occurred: The module named 'ApprovalModule' must be compiled using the JIT compiler, however, the necessary compiler '@angular/compiler' is not currently accessible

Issue: Error: The NgModule 'ApprovalModule' needs to be compiled using the JIT compiler, but '@angular/compiler' is not available. JIT compilation is not recommended for production environments. Consider using AOT mode instead. Alterna ...

Error message stating: "Form control with the name does not have a value accessor in Angular's reactive forms."

I have a specific input setup in the following way: <form [formGroup]="loginForm""> <ion-input [formControlName]="'email'"></ion-input> In my component, I've defined the form as: this.log ...

Executing multiple queries in a node.js transaction with Sequelize using an array

I am looking to include the updates on the clothingModel inside a transaction, with the condition that if it successfully commits, then update the reservationModel. This is the snippet of code I am attempting to refactor using sequelize.transaction tr ...

Ensuring TypeScript recognizes a class property as definitively initialized when set using a Promise constructor

I have a simple class definition that is giving me an error in TypeScript. class Container { resolveData: (s: string) => void // not definitely initialized error! data: Promise<string> constructor() { this.data = new Promise&l ...

Did the IBM MobileFirst client miss the call to handleFailure?

I am currently utilizing the IBM MFP Web SDK along with the provided code snippet to send challenges and manage responses from the IBM MobileFirst server. Everything functions properly when the server is up and running. However, I have encountered an iss ...

Launching the VS Code debugger feels like inviting my web app to a party

Recently, I've noticed an issue while debugging my vs code. It appears that the debugger hosts my app without me even running npm start. This behavior allows me to access my app in Chrome without initiating npm start. Normally, my app runs on port 300 ...