Returning Results from Alerts in Ionic 4
Last year I wrote a blog post about making code for displaying alerts reusable and testable by wrapping it into a function which returns the user's response as a promise. The sample was written in Ionic 3. The code doesn't work in Ionic 4 without modifications. Since I recently received a request for an Ionic 4 version of the code, I decided to write this follow-up post.
Unlike some other parts of Ionic 4, alerts didn't change much since Ionic 3. However, because the official documentation is now written using async
and await
instead of promises, I updated my code as well to better match the recommended coding style:
private async confirmationAlert(message: string): Promise<boolean> {
let resolveFunction: (confirm: boolean) => void;
const promise = new Promise<boolean>(resolve => {
resolveFunction = resolve;
});
const alert = await this.alertController.create({
header: 'Confirmation',
message,
backdropDismiss: false,
buttons: [
{
text: 'No',
handler: () => resolveFunction(false)
},
{
text: 'Yes',
handler: () => resolveFunction(true)
}
]
});
await alert.present();
return promise;
}
Although the function is now asynchronous and I use await
when calling create
and present
, I still need to return a Promise
which is resolved with the correct return value after the user clicks one of the alert buttons.
The calling function doesn't need to be aware of this implementation detail, though. It can treat the wrapper function just like any other asynchronous function:
public async onDelete() {
const confirm = await this.confirmationAlert(
'Do you really want to delete the entry?'
);
if (confirm) {
console.log('Deleted');
} else {
console.log('Canceled');
}
}
The majority of differences between the two samples are not because of API changes. They are a result of using more modern language constructs. A while back, I've written a blog post about updating code that uses promises to async
and await
. It was based on Angular's Tour of Heroes tutorial at the time. Although the tutorial has changed a lot since then and the changes I made aren't applicable to it anymore, you can still use the same approach for converting any code with promises to async
and await
.