如何在JavaScript中将构建器模式与异步方法调用结合在一起?

我想实现像这样的链接方法调用

observable
 .pipe(
  filter('foo'),add(3)
 )
 .subscribe(subscriber);

要使其正常工作,.pipe(...)的结果必须提供方法subscribe

我想允许通过pipe进行某些链接方法调用(例如async)。但是,这会中断我的工作,因为pipe返回的promise没有subscribe方法:

await observable
 .pipe(
  filter('foo'),add(3)
 )
 .subscribe(subscriber);

async pipe(...operators){
  ...
}

=> Uncaught (in promise) TypeError: observable.pipe(...).subscribe is not a function

我可以将我的主要代码重写为

observable
 .pipe(
  filter('foo'),add(3)
 ).then(pipeResult=>
  pipeResult.subscribe(subscriber);
 );

但是,我觉得阅读起来很丑。

=>有没有一种方法可以对方法调用链中的每个调用都应用await,而不仅仅是最后一个?

我希望有类似的东西

awaitEach observable
 .pipe(
  filter('foo'),add(3)
 )
 .subscribe(subscriber); 

编辑

  • 相关问题:

chaining async method calls - javascript

  • 借助Promises,我可以从同步调用转换为异步调用:

foo(){
 return new Promise(resolve=>{
   baa().then(arg=>resolve(arg))
 })
} 

但是,我需要另一个方向,例如:

pipe() {
   var result = undefined;
   await asyncCall(()=>{ //await is not allowed here; forces pipe to by async
     result = 5;
   });
   return result;
 }
iCMS 回答:如何在JavaScript中将构建器模式与异步方法调用结合在一起?

作为一种变通方法,我使用subscribe代理扩展了所产生的promise,并调用了我的实际subscribe方法:

pipe(...operators){

    let observable = this;

    let promise = new Promise(async (resolve) =>{
      for (let operator of operators){
       observable = await this._applyOperator(operator,observable);
      }
      resolve(observable);
    });

    promise.subscribe = (subscriber)=>{
      promise.then(resultingObservable =>{
        resultingObservable.subscribe(subscriber);
      })
    };

    return promise;
} 

如果您知道更好的解决方案,请告诉我。

本文链接:https://www.f2er.com/1989866.html

大家都在问