Home > Software design >  Return promise values to calling function in Angular
Return promise values to calling function in Angular

Time:02-16

I have created a promise to fetch values from a service and then return it trans and confidence to transcript and conf respectively inside save_data function. How will i use return those values to the calling function and rest of the code should not get executed till all the promise is returned successfully.

 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  => {
      
      
        });
      });
     

enter image description here

Value inside promise: enter image description here Any solution to resolve this issue, Thanks

CodePudding user response:

Resolve your promise with the trans and confidence results, and capture those when the promise resolves. As you have used async, use await. This also solves the this problem that your code has:

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();

  • Related