-3

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

user3653474
  • 3,393
  • 6
  • 49
  • 135
  • Move the "rest of code" inside the `then` callback, or put it in a function and call that function from within that `then` callback. Or make `save_data` an `async` function, and use `await` on `this.fetchTransValues()` (without `then`) – trincot Feb 15 '22 at 14:52
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – jonrsharpe Feb 15 '22 at 14:52
  • That `console.log(message)` logs _"Hello asynchronous world!"_ is not already enough of a hint? – Andreas Feb 15 '22 at 14:54
  • @trincot Thanks all for the solution, will i be able to use `trans` and `confidence` variable inside then block – user3653474 Feb 15 '22 at 15:00
  • No, for that you need to pass them to `resolve()` as argument, like so: `resolve({trans, confidence})`. Then `message` will have those as properties. – trincot Feb 15 '22 at 15:04
  • @trincot As you have told i have moved my code to then block but getting `ERROR TypeError: Cannot read properties of undefined (reading 'getTranscriptValue')` but this method is available and i have updated my complete code in question can you please check – user3653474 Feb 15 '22 at 15:07
  • That is because you use `this`, and the value of `this` is not the same when you use a callback `function`. Use an arrow function instead. Also, don't use `async` if you don't use `await`. – trincot Feb 15 '22 at 15:10
  • @trincot I'm using like this return new Promise((resolve, reject) => { setTimeout(function() { var trans = this.service.getTranscriptValue(); var confidence =this.service.getConfidenceValue(); }, 1000); }); but getting same error can you please provide some link for the same – user3653474 Feb 15 '22 at 15:31
  • I'm talking about the callback that is given to `then`. Just change all callbacks to arrow functions, and you won't have an error that relates to `this`. – trincot Feb 15 '22 at 15:44
  • @trincot In console error is in these lines of codes `var trans this.service.getTranscriptValue(); var confidence =this.service.getConfidenceValue();` inside `fetchTransValues` method – user3653474 Feb 15 '22 at 15:46
  • Can you edit your question and focus on the problem you are having now, with the most recent code? I am lost. Please remove **any** code that is not relevant to the problem. Make it minimal. Just enough to make the problem reproducible. – trincot Feb 15 '22 at 15:49
  • @trincot Yes i have updated my code, initially `save_recording` is called then i want rest of the code to execute in `save_recording` after `fetchTransValues` returns updated value, getting this error : `ERROR TypeError: Cannot read properties of undefined (reading 'getTranscriptValue')` can you ploease check, – user3653474 Feb 15 '22 at 15:55
  • Where do you use `message`? Do you need it at all? What is the purpose if `transcript_arr`, and of `confidence_arr`. They are never used. Are they relevant to your problem? Is the call to `this.http.post` relevant to your problem? – trincot Feb 15 '22 at 15:58
  • @trincot No i want to use only `trans` and `confidence` in the calling method don't need message, yes i will be using `confidence_arr` and `transcript_arr` – user3653474 Feb 15 '22 at 15:59

1 Answers1

1

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();
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thanks for the answer, getting this error `Property 'trans' does not exist on type 'Promise'.` service method actually returns array values that's why i was using `const` previously – user3653474 Feb 15 '22 at 16:10
  • Corrected now.. `const` is fine also. – trincot Feb 15 '22 at 16:11
  • Getting this error `Property 'trans' does not exist on type '{}'` – user3653474 Feb 15 '22 at 16:14
  • I turned my answer into a runnable snippet. It is important to change all callbacks (that use `this`) to arrow functions. – trincot Feb 15 '22 at 16:22
  • when i comment these lines `resolve({service_transcript, service_confidence});` then it is working but i can't use these values in calling function – user3653474 Feb 15 '22 at 16:25
  • Did you run the snippet in my answer? – trincot Feb 15 '22 at 16:26
  • When i use your code that is working on editor then also i'm getting the error that i have uploaded in the screenshot – user3653474 Feb 15 '22 at 16:35
  • I cannot reproduce that issue. Please provide the code that makes it possible to reproduce the issue for us. – trincot Feb 15 '22 at 17:14
  • Code is almost same will i have to define type also https://stackoverflow.com/questions/49854385/property-does-not-exists-on-type-using-promises as asked in this question? Value is also returned from the service as shown in screenshot – user3653474 Feb 15 '22 at 17:17
  • Definitely. I was dealing with this on the JavaScript level, as your original question was about asynchrony, but has gone through several revisions and is now a completely different question than it was from the start. And yes, this is related to typescript typing. – trincot Feb 15 '22 at 17:21
  • It got solved when i gave type `return new Promise<{ trans: any,confidence:any }>((resolve, reject) => {` Thanks for the solution, Should i use then block also because my main motive was next block should only execute after previous blocks of code returned proper results, or without then also it will work the same way – user3653474 Feb 15 '22 at 17:32
  • 1
    The `await` will make sure that the code below it is only executed later, when the promise has resolved, so no `then` is needed. – trincot Feb 15 '22 at 17:33