await表达式只允许在异步函数中使用

时间:2017-12-28 08:50:01

标签: angular typescript promise async-await ionic3

你能告诉我把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();
  }

1 个答案:

答案 0 :(得分:1)

通常你使用

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

如评论中所述。但是当前的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;
            }
          }