typescript async-await导致变量未定义

时间:2018-03-21 03:21:16

标签: angular typescript async-await

我有这个问题,我面临着vm_res未定义的问题 async update_vm_raw_device函数,函数update_vm_raw_device运行,但是值为udpated,如/mnt/tank/ds/test_file_test_VM_undefined,请注意最终未定义。

async customSubmit(value) {
  const path = value.raw_file_directory+ '/' + value.raw_filename+ '_'+ value.name;
    const payload = {}
    const vm_payload = {}
    ......SNIP..........
    this.ws.call('vm.get_sharefs').subscribe((get_sharefs)=>{
      if(!get_sharefs){
        this.ws.call('vm.activate_sharefs').subscribe((sharefs)=>{
          this.ws.call('vm.create', [vm_payload]).toPromise().then(vm_res => {
            // here the assignment happens, but  this.vm_res is undefined in 
            // async update_vm_raw_device function.
            this.vm_res = vm_res;
          });
        }
      )
      }
      else {
        this.ws.call('vm.create', [vm_payload]).toPromise().then(vm_res => {
          this.vm_res = vm_res;
        });
      }
    },)
    await this.update_vm_raw_device(vm_payload, this.vm_res);
  }

  async update_vm_raw_device(vm_payload: any, vm_res: number) {
  vm_payload.path = vm_payload.path+"_"+this.vm_res
   await this.ws.call('datastore.update'[vm_payload])]).toPromise().then(
       res=>{});}

1 个答案:

答案 0 :(得分:0)

async/await与此无关。

据我所知,this.vm_res只能在subscribe回调中设置,在您致电this.update_vm_raw_device()之前不会发生这种情况。

您是否打算将this.update_vm_raw_device()的调用放在订阅处理程序中?也许在设定了这个值之后?