【问题标题】:Awaiting a Promise result within an Angular RxJS Observable Method在 Angular RxJS 可观察方法中等待 Promise 结果
【发布时间】:2020-05-18 15:41:32
【问题描述】:

下面的方法应该是一个 Observable,它需要来自 Promise 函数的一些数据才能继续执行。

    async function observableFunc(): Observable<string> {
      const response = await promiseFunc()
      return anotherObservableFunc(response)
    }

这会引发错误,因为异步函数应该返回一个承诺。

我尝试使用.toPromise(),但后来我无法使用.pipe() 执行以下操作:

observableFunc().pipe(...)

开发人员在这里做什么? ????

【问题讨论】:

    标签: angular typescript promise rxjs observable


    【解决方案1】:

    您可以使用from,它将Promise(除其他外)转换为Observable

    function observableFunc(): Observable<string> {
      return from(promiseFunc()).pipe(
        concatMap(() => anotherObservableFunc())
      );
    }
    

    我使用concatMap,因为它更具描述性。它基本上是说,等到前一个 Observable 完成(Promise 会这样做),然后订阅另一个 Observable

    虽然在这种情况下,使用mergeMapswitchMap 没有区别。从语义上讲,concatMap 更合适

    【讨论】:

      【解决方案2】:

      你必须将 promise 转换为 observable

      function observableFunc(): Observable<string> {
        return from(promiseFunc())
         .pipe(
            swithMapTo(anotherObservableFunc())
          );
      
      }
      

      我假设 anotherObservableFunc 返回一个 observable。

      【讨论】:

        【解决方案3】:

        试试这个

        promiseFunc(){
              return new Promise(function(resolve, reject) {
                resolve('start of new Promise');
              });
          }
        

        以这种方式创建一个新的承诺

        你也可以这样等几秒试试

        promiseFunc(){
          return new Promise((resolve, reject) => {
            setTimeout(() => resolve("done!"), 1000)
          });
        }
        

        它的调用会像

        async function observableFunc(){
              const response = await promiseFunc()
              // no do whatever you like as next statement will be executed after response gets it value
        
            }
        

        【讨论】:

        • 关于定义 promiseFunc 方法的问题,关于如何在可观察方法中实际等待其响应
        猜你喜欢
        • 1970-01-01
        • 2020-03-12
        • 2017-10-12
        • 2019-03-25
        • 2017-06-11
        • 2017-07-01
        • 1970-01-01
        • 2019-05-15
        • 1970-01-01
        相关资源
        最近更新 更多