使用async-await和订阅

时间:2018-03-17 05:20:38

标签: node.js angular

我想使用async-await来修复我写的callback hell。任何人都可以请解释我如何使用async-await,以便调试代码不那么可怕。

              this.ws.call('vm.image_path', ['RancherOS']).subscribe((img_path)=>{
            if(!img_path){
              this.dialog.Info('CHECKSUM MISMATCH', 'system checks failed to verify ISO, please try rebooting Virtual Machine');
              this.loader.close();
              return;
            };
            this.ws.call('vm.decompress_gzip',[img_path, this.raw_file_path]).subscribe((decompress_gzip)=>{
              this.ws.call('vm.raw_resize',[this.raw_file_path, this.raw_file_path_size]).subscribe((raw_resize)=>{
                this.ws.call('vm.start',[this.cards[index].id]).subscribe((vm_start)=>{
                    this.loader.close();
                    if(!vm_start){
                      this.dialog.Info('ERROR', 'vm failed to start, please check system log.');
                      return;
                    }
                    this.refreshVM(index, this.cards[index].id);

                  });
                },
                (error_raw_resize)=>{
                  this.loader.close();
                  new EntityUtils().handleError(this, error_raw_resize);
                })
            },(decompress_gzip)=>{
              this.loader.close();
              new EntityUtils().handleError(this, decompress_gzip);
          });
          },(error_img_path)=>{
            this.loader.close();
            new EntityUtils().handleError(this, error_img_path);
          });

1 个答案:

答案 0 :(得分:1)

使用RxJs toPromise运算符使生活更简单

<强> SomeService

import 'rxjs/add/operator/toPromise';

// ..

public async someFunction() {
    let response = await this._http.get<any>(this.apiURL).toPromise();
    return response;
}

要调用方法,

public async getProducts() {
    try {
        let response = await this.someService.someFunction();
        // do something with response
    } 
    catch (e) {
        // handle error here
    }
}

IMO以这种方式编写异步方法更加清晰和可调试。