角度等待不等待函数完成

zif*_*yan 1 async-await typescript ionic-framework angular

我正在从 cordova 插件调用异步函数。然而等待并没有真正起作用。

export class MationLiteService implements IgatewayService {
  async getGroupAllInfo(gatewayId: string, account: string, decryptedpasswd: string) {

// some codes
        return await cordova.plugins.MationPlugin.getGroupAllInfo(data, async (response) => {

        const json: JSON = JSON.parse(response);
        console.log('responseaaaaa:' + response);
        return json;
      }, (error) => {
        console.log('error: ' + error);
      });
  }
}
Run Code Online (Sandbox Code Playgroud)

这是网关管理器类

export class GatewayManagerService {
 public  getGroupAllInfo(gatewayType: string, gatewayId: string, account: string, decryptedpasswd: string) {
    return this.gatewayFactoryService.getGateway(gatewayType).getGroupAllInfo(gatewayId, account, decryptedpasswd);
  }
}
Run Code Online (Sandbox Code Playgroud)

我就是这么称呼它的

  async getAllInfo2(){
     this.facadaService.GetGatewayManagerService().getGroupAllInfo('mation-lite', this.zifan, 'admin', '5555').then((response) => {
        console.log(response);
     });
    //await this.facadaService.GetGatewayManagerService().test('mation-lite');

  }
Run Code Online (Sandbox Code Playgroud)

当我尝试打印响应时,它给了我未定义的信息。

Nic*_*wer 5

await只适用于 Promise,并且看起来MationPlugin.getGroupAllInfo使用回调来实现异步,而不是 Promise。您需要自己将其包含在承诺中。

getGroupAllInfo(gatewayId: string, account: string, decryptedpasswd: string) {
  return new Promise((resolve, reject) => {
    cordova.plugins.MationPlugin.getGroupAllInfo(data, (response) => {
      const json: JSON = JSON.parse(response);
      resolve(json);
    }, (error) => {
      reject(error);
    });
})
Run Code Online (Sandbox Code Playgroud)