【问题标题】:await expression is only allowed within an async functionawait 表达式只允许在异步函数中使用
【发布时间】:2018-01-18 15:40:53
【问题描述】:

你能告诉我把async关键字放在哪里吗?我尝试了很多地方。但同样的错误。

  async addNewCategory() {
    let alert = this.alertCtrl.create({ 
      title: 'New Category',
      inputs: [
        {
          name: 'name',
          placeholder: 'Category',
        },
      ],
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Done',
          handler: (data:Category) => {
            if (data.name != '') {
              //Error shows here
              await this.categoryProvider.isCategoryAlreadyExist(data.name, this.projectId); 
            } else {
              this.showToast.showErrorToast('Invalid Category');
              return false;
            }
          }
        }
      ]
    });
    alert.present();
  }

【问题讨论】:

  • async (data:Category) => {...
  • 试过了。它显示了这个错误。 [ts] Type '{ text: string; handler: (data: Category) => Promise<false>; }' is not assignable to type 'AlertButton'. Types of property 'handler' are incompatible. Type '(data: Category) => Promise<false>' is not assignable to type '(value: any) => boolean | void'. Type 'Promise<false>' is not assignable to type 'boolean | void'. Type 'Promise<false>' is not assignable to type 'void'. (property) handler: (data: Category) => Promise<false> @deezg
  • @Sampath 好吧,看起来无论你在哪里传递这个对象都不支持异步处理程序。
  • 哦.. :(你能告诉我解决方法吗?@Bergi
  • 这似乎是 ionic 2+ check issue987654321@中警报的类型声明问题

标签: angular typescript promise async-await ionic3


【解决方案1】:

一般你用

async (data:Category) => {...}

如 cmets 中所述。但是当前的 alertController 没有采用 async handler,因为它的类型定义按照这个 issue

export interface AlertButton {
  text?: string;
  role?: string;
  cssClass?: string;
  handler?: (value: any) => boolean|void;
}

警报按钮定义here

您将需要使用更传统的方式使用then

handler: (data:Category) => {
            if (data.name != '') {
              //Error shows here
              this.categoryProvider.isCategoryAlreadyExist(data.name, this.projectId)
                .then(()=>alert.dismiss()); 
            } else {
              this.showToast.showErrorToast('Invalid Category');
              return false;
            }
          }

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2016-02-08
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多