如何让 processData 函数等待 Angular 中 getData 函数的结果?

How do I make processData function wait for the results from my getData function in Angular?

我的 getData 函数进行了一次 api 调用,然后将每个返回的对象放入一个数组中。然后返回数组。我现在需要我的 processData 函数来等待 getData 函数的结果,然后进一步处理它。目前,当我 console.log(cleaningData) 我对 async/await 做错了什么时,我没有得到任何结果?我错过了什么?


getData() {
 var dataBucket = [] 
 this.https.get('https:******FAKEURL*******').subscribe((response: any) => {
    console.log(response.data)
    for(let i = 0 ; i < response.data.length ; i++) {
       dataBucket.push(response.data[i])
    }
  });
  console.log(dataBucket);
  return dataBucket;     
 }

async processData() { 
  let cleaningData = await this.getData();
  console.log(cleaningData);
  //do something with cleaningData
}

在angular中,您通常遵循异步函数的另一种逻辑。您声明当异步函数 returns 带有订阅时应该发生什么。那么当它 returns 从您的订阅代码块开始(而不是从您等待异步函数的其他地方)开始时应该发生什么?

    getData() {
    
        this.https.get('https:******FAKEURL*******').subscribe((response: any) => {
            
            var dataBucket = []   <-----this should be here declared
    
            console.log(response.data)
    
            for(let i = 0 ; i < response.data.length ; i++){
             
              dataBucket.push(response.data[i])
            }
    
          this.processData(response)  <-------you call that here
          });
      }
    
    processData(response: any){    <-----you don't need async and await
    
      // <----- here you can do anything with the response from getData() 
    
      console.log(cleaningData);
    
      //do something with cleaningData
   }