【问题标题】:Return promise values to calling function in Angular将承诺值返回给 Angular 中的调用函数
【发布时间】:2022-02-16 01:21:00
【问题描述】:

我已经创建了一个从服务中获取值的承诺,然后在 save_data 函数中分别将其返回到 transconfidencetranscriptconf。我将如何使用将这些值返回给调用函数,并且在所有承诺都成功返回之前,其余代码不应执行。

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

承诺中的价值: 任何解决此问题的解决方案,谢谢

【问题讨论】:

  • 将“其余代码”移动到then 回调中,或者将其放入一个函数中并从该then 回调中调用该函数。或将save_data 设为async 函数,并在this.fetchTransValues() 上使用await(不带then
  • console.log(message) 记录 "Hello asynchronous world!" 提示还不够吗?
  • @trincot 谢谢大家的解决方案,我可以在块内使用transconfidence 变量
  • 不,因为您需要将它们作为参数传递给resolve(),例如:resolve({trans, confidence})。然后message 会将这些作为属性。

标签: angular typescript promise


【解决方案1】:

使用 transconfidence 结果解决您的承诺,并在承诺解决时捕获这些结果。如您使用async,请使用await。这也解决了您的代码存在的this 问题:

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

【讨论】:

  • 感谢您的回答,收到此错误Property 'trans' does not exist on type 'Promise<unknown>'. 服务方法实际上返回数组值,这就是我之前使用const 的原因
  • 现在更正了。const 也可以。
  • 收到此错误Property 'trans' does not exist on type '{}'
  • 我把我的答案变成了一个可运行的 sn-p。将所有回调(使用this)更改为箭头函数非常重要。
  • await 将确保它下面的代码只在以后执行,当 promise 解决时,所以不需要then
猜你喜欢
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-05
  • 2019-04-15
  • 2016-06-15
  • 2019-01-23
相关资源
最近更新 更多