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

Using Angular2, summon numerous ajax requests and then patiently wait for the results

I'm facing an issue with my Angular code. Here are the functions I've been working on: private callUserInfo(): any { this.isLoading = true; return this._ajaxService.getService('/system/ping') .map( result => { this.user ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

Adding a line break ( ) in a paragraph within a TypeScript file and then transferring it to HTML does not seem to be functioning properly

Angular Website Component: HTML file <content-section [text]="data"></content-section> TypeScript file data = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's stand ...

Tips for efficiently combining mergeMap observables and providing a singular value for the entire observable

Consider this particular case involving TypeScript/angular with rxjs 6.5: main(){ const items = ['session', 'user']; const source: Observable<any> = from(items); source .pipe( ...

Angular is programmed to detect any alterations

Upon detecting changes, the NgOnChanges function triggers an infinite service call to update the table, a situation that currently perplexes me. Any assistance on this matter would be greatly appreciated. Many thanks. The TableMultiSortComponent functions ...

Show website traffic using TypeScript visitor counter

I need help adding a visitor counter to my website. I initially tried using the API from , but it seems that the server is currently down and I can no longer use it. I found another API at . How can I retrieve count data from this specific API endpoint ...

«IntelliJ: Effortless Live Reload with Spring Boot and Angular»

For my software development projects, I often work with a spring boot maven project alongside an Angular 5 project. To optimize the workflow, I usually start by building the "dist" folder using the npm run build:prod command and then incorporating it into ...

- "Is it possible to extract values from an optional variable?"

Is there a method to access individual variables from the data returned by the reload method? let reloadProps: ReloadProps | undefined; if (useClientSide() === true) { reloadProps = reload(props.eventId); } const { isTiketAdmin, jwt, user ...

What is the best way to dynamically generate and update the content of a select input in an Angular form using reactive programming techniques?

I have successfully developed an Angular reactive form that includes a select field populated dynamically with values retrieved from an API call. In addition, I have managed to patch the form fields with the necessary data. My current challenge is to dyn ...

Tips for activating automatic building of packages when utilizing pnpm install?

Our unique project is utilizing a combination of pnpm, workspace, and typescript in adherence to the monorepo standard. Upon cloning the repository, we execute a pnpm install command to download dependencies and establish links between local packages. De ...

The element is inherently an 'any' type as the expression of type 'number' does not have the capability to index type 'Object'

Hey there, I'm currently in the process of learning Angular and following along with the Note Mates tutorial on YouTube. However, I've hit a stumbling block as I attempt to implement sorting by relevancy. The issue lies with the code snippet belo ...

Generate dynamic property values based on calculations

I am facing a challenge with a form that I have designed. Could you guide me on how to dynamically update the value of the calculate field (contingency) whenever the user modifies the values of budget1 and budget2? I have attempted several approaches witho ...

The issue of linking .then() functions

I've been struggling to grasp the concept of Promises/then-ables for a while now. Currently, I am working with NextJS. My goal is to chain together the following steps: Retrieve data from an API Save the data Modify the data to create a component (w ...

The conventional method for including React import statements

I'm curious if there is a standard convention for writing import statements in React. For instance, I currently have the following: import React, { useState, FormEvent } from 'react'; import Avatar from '@material-ui/core/Avatar'; ...

Expanding on Angular's virtual scroll feature: automatically add new items as you reach the bottom of the

I'm facing a challenge in my Angular application where I want to implement virtual scroll. The items displayed on the list are the outcome of a remote paged search. My goal is to fetch more results (trigger the next page) every time I scroll down to t ...

What is the best way to utilize a negative glob pattern?

After our build process completes, we end up with both e2015 and es5 bundles. For example, in the dist directory, you will find files like these: /common-es2015.7765e11579e6bbced8e8.js /common-es5.7765e11579e6bbced8e8.js /custom.js We are trying to set u ...

The absence of the Angular property has been detected

Let's say you have the following model in your application. export class Instructor{ firstname:string; lastname:string; } export class Course { ID: number; title: string; crn: string; instructor:Instructor; } In order to reset a form, you can us ...

What is the best way to create an instance method in a subclass that can also call a different instance method?

In our programming project, we have a hierarchy of classes where some classes inherit from a base class. Our goal is to create an instance method that is strongly-typed in such a way that it only accepts the name of another instance method as input. We d ...

Issue with Angular 9 application: Unable to properly render form fields within a Material Design Dialog

I'm currently developing a "Tasks" application using Angular 9 and PHP. I've encountered an error that says Cannot find control with name: <control name> when attempting to pre-fill the update form with data. Here is the form template: &l ...