【问题标题】:Is there a way to use async-await or to hold the execution stack while data is returned from subscription有没有办法在订阅返回数据时使用 async-await 或保持执行堆栈
【发布时间】:2019-07-01 11:26:24
【问题描述】:

我有一个函数调用一个函数,该函数又订阅 HTTP 调用。我知道订阅不会返回 async await 期望的承诺,但有没有办法可以限制执行,直到返回数据。

我尝试过使用异步等待,但没有运气 我可以将要执行的代码放入订阅中 但我不想这样做,因为我的功能不是为此而设计的(试图遵循单一责任原则)

async function a () {
   await subscription_return();
   code to be executed after subscription has got the data
}

subscription_return(){
     this.http.getDataFromService().subscribe((response) => {});
}

【问题讨论】:

  • 好吧,您可能不应该在其他函数中订阅。只需返回 observable 并在您的第一个函数中订阅。

标签: angular asynchronous async-await rxjs


【解决方案1】:

你可以await一个promise,像这样:

async function a () {
   const data = await subscription_return();
   // code to be executed after subscription has got the data
}

subscription_return(){
     return this.http.getDataFromService().toPromise();
}

【讨论】:

  • 谢谢,它成功了,只是想知道,在使用http 调用时,我们可以确保订阅将在获取数据后结束,因此我们可以使用 toPromise(),但假设我有订阅这永无止境,就像点击一个按钮,那么如何实现上面的问题?
【解决方案2】:

您可以返回Observable 并在需要组件上使用订阅,例如您的 service.component.ts 文件中包含以下代码。

  subscription_return(): Observable<any> {
      return  this.http.getDataFromService();
  }

在你的实际组件中,你可以像订阅它一样

this.serviceinstance.subscription_return().subscribe((response) => {});

【讨论】:

    【解决方案3】:

    对于不存在 toPromise 的环境的通用解决方案,只需将您的异步调用包装在一个 Promise 中:

    async function a () {
       const data = await subscription_return();
       //code to be executed after subscription has got the data
    }
    
    subscription_return(){
        return new Promise((resolve, reject) => {
            this.http.getDataFromService().subscribe((response) => { resolve(response); });
        });
    }
    

    带有超时的演示来模拟您的异步功能:

    async function a () {
       console.log('start');
       const data = await subscription_return();
       console.log('result: ', data);
    }
    
    function subscription_return(){
        return new Promise((resolve, reject) => {
            setTimeout(function(){
                console.log('async done');
                resolve('data');
            }, 100);
        });
    }
    
    a();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-09
      • 2020-04-06
      • 2012-12-02
      • 2021-12-13
      • 2018-03-27
      • 2019-10-08
      • 2020-02-16
      • 2020-07-14
      相关资源
      最近更新 更多