Search code examples
javascripttypescriptaurelia

How to use async function in keypress.delegate event


I need to pass an asynchronous function to a keypress event in my html So far without an asynchronous function, my function must return true so that I can write to my input field otherwise I'm stuck

Here is my html

<input type="text" class="form-control" keypress.delegate="onEnterKeyPressedAsync($event)" value.bind="newItem[valueField] & validateForm" 
      check-field="field:SCHEMA.USER_MAIL;format:alphanum;is-required.bind:true;" maxlength="255">

Here is my typescript file

public async onEnterKeyPressedAsync($event : any) : Promise<boolean> {
 if ($event.which === 13 && this.items.length > 0) {
  const isValid = await this.addItemFormValidVM.validateAsync();
  if (this.saveAsync && isValid) {
    this.saveAsync({newItem : this.newItem});
    this.newItem = this._initializeNewItem();
    this.fieldIsVisible = false;
    this.addItemFormValidVM.clear();
  }
}
return true;

}

My function is triggered by the keypress event but it blocks input in my input field. I already tried to return Promise.resolve(true) in my function but without success

My function must be asynchronous because I have to wait for a form validation

Currently, I can't write in my input field unless I remove the async from this function


Solution

  • To resolve your problem, onEnterKeyPressedAsync must not be an async function. They are two ways to do it.

    Using then instead of await

    public onEnterKeyPressedAsync($event : any) : Promise<boolean> {
     if ($event.which === 13 && this.items.length > 0) {
       this.addItemFormValidVM.validateAsync().then(isValid => {
        if (this.saveAsync && isValid) {
          this.saveAsync({newItem : this.newItem});
          this.newItem = this._initializeNewItem();
          this.fieldIsVisible = false;
          this.addItemFormValidVM.clear();
        }
       });
     }
     return true;
    }
    

    Or split your code with two function, externalise your async code in another function, then, called it without await :

    private async relevantFunctionNameAsync() {
      const isValid = await this.addItemFormValidVM.validateAsync();
      if (this.saveAsync && isValid) {
        this.saveAsync({newItem : this.newItem});
        this.newItem = this._initializeNewItem();
        this.fieldIsVisible = false;
        this.addItemFormValidVM.clear();
      }
    }
    
    public onEnterKeyPressedAsync($event : any) : Promise<boolean> {
     if ($event.which === 13 && this.items.length > 0) {
       relevantFunctionNameAsync();
     }
     return true;
    }