在打字稿中编写 if..else 块并在其间进行网络调用的更好方法

我发现自己写了很多这样的代码;


if(cond){

   /*do some network call */

   this.networkService.invoke(params).subscribe((res) => {

      this.doSomething();

   })

}else{

   /* do something without calling the network */

   this.doSomething();

}

本质上,this.doSomething();无论是否满足条件都必须调用。如果cond === true,则进行一些网络调用,然后this.doSomething()。有没有更好的方法来编写这样的代码?


繁花不似锦
浏览 106回答 2
2回答

慕容3067478

通过将您的 observable 转换为 promise 并使父函数异步,您可以这样做:async parentFunction() {    ...    cond && await this.networkService.invoke(params).toPromise()    this.doSomething();}

慕尼黑的夜晚无繁华

也许这不是你要问的,但大多数时候(恕我直言)这种代码的问题是它有时是同步的,有时是异步的。为避免这种情况,您可以使用rxjs运算符of始终采用异步方式。我最近用缓存服务做了类似的事情。这里的想法是Observable即使数据已经加载,也总是返回一个;private data: SomeData[] = null;private isLoadedOrOnItsWay = false;private subject: Subject<SomeData[]> = new Subject<SomeData[]>();constructor(private dataService: DataService) { }public getAll(): Observable<SomeData[]> {&nbsp; &nbsp; if (!this.isLoadedOrOnItsWay) {&nbsp; &nbsp; &nbsp; &nbsp; this.isLoadedOrOnItsWay = true;&nbsp; &nbsp; &nbsp; &nbsp; this.dataService.getData<SomeData[]>().subscribe(x => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Load from service...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.data = x;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.subject.next(x);&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; } else if (this.data) {&nbsp; &nbsp; &nbsp; &nbsp; // Get from cache&nbsp; &nbsp; &nbsp; &nbsp; return of(this.data);&nbsp; &nbsp; }&nbsp; &nbsp; // Return subject and wait for data to be loaded&nbsp; &nbsp; return this.subject;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript