Sampath
Sampath

Reputation: 65870

await expression is only allowed within an async function

Could you tell me where to put async keyword? I have tried many places.But same error.

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

Upvotes: 1

Views: 8142

Answers (1)

Suraj Rao
Suraj Rao

Reputation: 29614

Generally you use

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

as mentioned in the comments. But the current alertController does not take an async handler because of its type definitions as per this issue.

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

Alert Button definition here.

You will need to use the more traditional way of using 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;
            }
          }

Upvotes: 1

Related Questions