I'm playing around with Promises in Angular 14. While I do understand the basics of Promises, I couldn't understand how the button click event know when to await an async event handler that returns a Promise versus just executing an event handler that simply returns void.
I expect to see something like this <button (async click)="await runAsync()">Run async</button> on the component HTML template, but obviously that's not going to work. So how does it work?
Sample code below for comparison:
<button (click)="runSync()">Run sync</button>
<p>Count: {{ count }}</p>
<hr />
<p>How this button know that the event handler it is calling is async?</p>
<button (click)="runAsync()" [disabled]="disabled">Run async</button>
<p>Value: {{ value }}</p>
<p>Error: {{ error }}</p>
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
name = 'Angular';
count: number;
value!: number;
error!: number;
disabled: boolean;
ngOnInit() {
this.count = 0;
this.disabled = false;
}
runSync(): void {
this.count++;
}
async runAsync(): Promise<void> {
try {
this.disabled = true;
this.value = await this.getRandomValue(2000);
} catch (e) {
this.error = <number>e;
} finally {
this.disabled = false;
}
}
private getRandomValue(delay: number): Promise<number> {
return new Promise<number>((resolve, reject) => {
const value = Math.floor(Math.random() * 10);
console.log(value);
if (value < 6) setTimeout(() => resolve(value), delay);
else reject(value);
});
}
}
Link to code: https://stackblitz.com/edit/angular-ivy-85kph9?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts
Thanks in advance!