【问题标题】:angular await does not wait for the function to finish角度等待不等待函数完成
【发布时间】:2020-06-10 09:40:45
【问题描述】:

我正在从 cordova 插件调用异步函数。但是 await 并没有真正起作用。

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);
      });
  }
}

这里是网关管理器类

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

我是这样称呼它的

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

  }

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

【问题讨论】:

  • getGroupAllInfo 返回什么类型?这是 Typescript - 我们喜欢类型!
  • 对不起,我对这些异步函数还是新手,回调将返回一个字符串。函数本身不会返回任何东西。但尼古拉斯塔的回答效果很好。我写代码的时候不理解promise和callback的概念。

标签: angular typescript ionic-framework async-await


【解决方案1】:

await 仅适用于承诺,看起来MationPlugin.getGroupAllInfo 使用回调来实现其异步性,而不是承诺。您需要自己将其包装在一个承诺中。

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);
    });
})

【讨论】:

    猜你喜欢
    • 2019-06-16
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多