如何等待订阅功能以角度 8 完成?

she*_*haf 6 wait subscribe observable async-await angular8

我想等待一个函数完成,然后再执行它旁边的函数。我有一个名为getData() 的函数,其中发生了 http 调用,它返回一个 observable。第二个函数checkDuplicate()我们订阅了该函数getData()。我们有第三个函数,称为proceed(),我们在其中调用checkDuplicate()函数,一旦checkDuplicate()函数完成,我们就会调用alert("finished")。但这里的问题是在checkDuplicate()函数完成之前,警报已经被触发。

找到代码以获得更好的说明:

getData(): Observable<any>{
  return this.http.get<any>(URL...);
}

checkDuplicate(){

return this.getData().subscribe(response => {
   if(response){
      console.log("Inside");
  }
});
}

proceed(){
 this.checkDuplicate();
 console.log("finished");
}
Run Code Online (Sandbox Code Playgroud)

实际结果

完成的

里面

预期结果

里面

完成的

我试过asyn/await等待 checkDuplicate() 函数完成。但是还是没有用。如果您分享解决方案,将不胜感激。提前致谢 !!!

And*_*tar 8

异步编程的陷阱。这是一个带有承诺的解决方案(您也可以使用可观察量):

getData(): Observable<any>{
  return this.http.get<any>(URL...);
}

async checkDuplicate(){
  var response = await this.getData().toPromise();
  if (response) {
      console.log("Inside");
  }
}

async proceed(){
 await this.checkDuplicate();
 console.log("finished");
}
Run Code Online (Sandbox Code Playgroud)