如何通过 line/How 异步地 运行 函数行到 运行 函数?

How to run a function line by line/How to run a function Asynchronously?

我正在尝试 运行 按顺序执行此功能。输出应该是 纬度长度, 纬度 A, 纬度 B

但我得到的输出是 纬度长度, 纬度 B, 纬度 A

我想先处理“this.adminService.getUserList().subscribe(res => {}”,但它是在 makeAnAPICall() 函数完成后才处理的。 我的代码如下:

 async makeAnAPICall():void {
     console.log("latitude length",this.latitude.length);
     this.latitude = [];
     this.longitude = [];
     delay(2000);

    await this.adminService.getUserList().subscribe(res => {
       for(let i =0; i < res.length; i++) {
         this.latitude.push(res[i].latitude);
         this.longitude.push(res[i].longitude);
       };
       console.log("lat length A",this.latitude.length)
     }); 
    
    

     console.log("lat length B ",this.latitude.length);
  }

您需要先将您的 observable 转换为 promise。

async makeAnAPICall():void {
     console.log("latitude length",this.latitude.length);
     this.latitude = [];
     this.longitude = [];
     delay(2000);
     const res = await this.adminService.getUserList().first().toPromise();
   
       for(let i =0; i < res.length; i++) {
         this.latitude.push(res[i].latitude);
         this.longitude.push(res[i].longitude);
       };
       console.log("lat length A",this.latitude.length)
     console.log("lat length B ",this.latitude.length);
  }