The use of await can only occur inside an async function

Can someone explain the proper placement of the async keyword for me? I've tried a few different spots, but keep encountering the 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 != '') {
              //The error seems to be cropping up here
              await this.categoryProvider.isCategoryAlreadyExist(data.name, this.projectId); 
            } else {
              this.showToast.showErrorToast('Invalid Category');
              return false;
            }
          }
        }
      ]
    });
    alert.present();
  }

Answer №1

Typically, the recommended syntax is:

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

This is commonly suggested in the comments. However, due to the type definitions of the current alertController, it does not support an async handler. This limitation is discussed in this issue.

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

You can find the definition for Alert Button here.

In such cases, you will have to resort to the more traditional method of using then.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The logs of both the frontend and backend display an array of numbers, but surprisingly, this data is not stored in the database

I am attempting to recreate the Backup Codes feature of Google by generating four random 8-digit numbers. for(let i = 0; i < 4; i++) { let backendCode = Math.floor(Math.random() * (99999999 - 10000000 + 1) + 10000000); backendCodes.push(back ...

Angular: Implementing default nested routes

I am currently facing a challenge with routing in my Angular application. I have set up a page within a router-output on the route /products. This page contains another router-output which will display one of two possible children routes (/products/profess ...

Functions designed to facilitate communication between systems

There is an interface that is heavily used in the project and there is some recurring logic within it. I feel like the current solution is not efficient and I am looking for a way to encapsulate this logic. Current code: interface Person { status: Sta ...

Modification of encapsulated class in Angular is not permitted

Within Angular, a div element with the class "container" is automatically created and inserted into my component's HTML. Is there a way to modify this class to "container-fluid"? I understand that Angular utilizes encapsulation, but I am unsure of how ...

Transferring information between two distinct components

I am facing an issue where I have a list of stores shown in an unordered list, and when this list is initialized the ngOnInit() function retrieves data for all the stores. However, I want to be able to send the store data from each list element to the stor ...

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...

Add a custom design to the Material UI menu feature

I am currently trying to implement a custom theme using the following code: import Menu from '@material-ui/core/Menu'; import { createStyles, withStyles, Theme } from '@material-ui/core/styles'; const myMenu = withStyles( ( theme: The ...

Angular auto-suggest components in material design

Can someone assist me in resolving my issue? I am trying to incorporate an autocomplete feature with a filter into my form. .ts file : contactArray; selectedContact: IContact; myControl = new FormControl(); filteredContact: Observable<string[] ...

Using child routes in eager loaded components can be achieved without making any changes to

In many tutorials, I have noticed that RouterModule.forChild(..) is commonly used for lazy loading. However, I am of the opinion that this forChild method can also be utilized for eager loading. Its advantage lies in the fact that routes can be configured ...

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...

Ways to utilize a field from an interface as a type of index

interface Mapping { "alpha": (a: string) => void "beta": (b: number) => void } interface In<T extends keyof Mapping> { readonly type: T, method: Mapping[T] } const inHandlers: In<"alpha"> = { type ...

Error encountered on login page: The protocol 'http' does not exist (related to HTML, TypeScript, Angular2, and JavaScript)

Screenshot of the issue: Access the complete project here: Link to a Plunker example of a log-in screen: http://plnkr.co/edit/j69yu9cSIQRL2GJZFCd1?p=preview (The username and password for this example are both set as "test") Snippet with the error in ...

TypeScript in Angular causing lodash tree shaking failure

I am currently working on a large project that involves TypeScript. Various attempts have been made to optimize the use of lodash in my project. Before making any conclusions, I believe it is important to review the outcomes of my efforts. The command I ...

React did not allow the duplicate image to be uploaded again

I've implemented a piece of code allowing users to upload images to the react-easy-crop package. There's also an "x" button that enables them to remove the image and upload another one. However, I'm currently facing an issue where users are ...

Why is the mappable Observable lost after using Angular 5's HttpClient?

Why is Angular 5 httpclient causing me to lose the observable after mapping? Am I overlooking something crucial in my code? The following is my code snippet: getRepos(org:string):Observable<any>{ let params = new HttpParams().set('org&ap ...

Is it possible to modify the variables in a SCSS file within an Angular 2 project?

Currently, I am working with Angular 2 using a SCSS style. My challenge is to retrieve data from a server in order to change a specific variable within the component's style - specifically a percentage value. You can view the SCSS and HTML code here. ...

How to disable typescript eslint notifications in the terminal for .js and .jsx files within a create-react-app project using VS Code

I'm currently in the process of transitioning from JavaScript to TypeScript within my create-react-app project. I am facing an issue where new ESLint TypeScript warnings are being flagged for my old .js and .jsx files, which is something I want to avo ...

Running multiple instances of Chrome to execute all scenarios sequentially within a single feature file in Protractor

I need to run all scenarios in multiple instances of a browser. I've set the maximum instance value in capabilities, but only one instance of Chrome opens and the tests run sequentially. How can I ensure that the tests run in multiple instances simult ...

Issue with file uploading in Angular 9 as the uploaded file is not being added to the

I've set up a form group in the HTML of my Angular 9 app that includes an upload feature for files. The file upload works fine when calling the handleFileInput function, as I can confirm from the console log output. However, even though the file gets ...

Position the float input to the right on the same line as an element

This Angular code contains a challenge where I aim to have text at the start of a column and an input box on the right side of the page, both aligned on the same line. The issue lies in the code which floats the input to the right but disrupts the alignme ...