Ionic 3: Better Dialogs with async/await

Manuel Heidrich
prototype.berlin
Published in
2 min readSep 4, 2018

--

When building a mobile app with Ionic there is a good chance you will want to display confirm dialogs to your users to ask them if they really want to do something, for example before logging them out of your application.

Fortunately Ionic comes with an AlertController that can handle dialogs like alerts, confirms and prompts. Unfortunately, though, the example usage explained in the Ionic docs is kind of clumsy and hard to read. That’s why I decided to develop a better approach. In this post I am going to explain why and how I did that. (tl;dr, just take me to the solution!)

So let’s look at an example based on the Ionic docs where you ask for confirmation before logging out the user:

So this works fine of course, but I think it is not the most beautiful solution.

Why, you ask?

You would have to read through lots of lines of code to see what is actually happening when the user confirms the logout. I usually like to split up huge methods into smaller ones, also keeping the separation of concerns principle in mind.

So what I usually did was splitting up the code into two methods, one responsible for displaying the dialog and one responsible for the actual logout process:

That seems better, but the there are still a lot of lines to read until you reach the actual logout method. I also did not like this solution very much because of semantics. The method called logout() does not do the actual logging out and I think a button labeled “Logout” should call a method with a similar name and not something like showLogoutConfirmation().

So now what?

async/await

As the post title might reveal my preferred solution is async/await. I had this idea while browsing through the documentation of the upcoming Ionic 4 release where the AlertController will be promisified by default. So why not use this strategy in Ionic 3?

That’s what I came up with and what I really like using right now for dialogs:

We have a method called logout() and one called confirmLogout(). The code is easy to read and each method does exactly what you would expect from their names.

I hope you like this solution and if you have any ideas or questions, please feel free to comment below!

--

--

Manuel Heidrich
prototype.berlin

Full Stack JavaScript Developer in Berlin. Ionic, Cordova, Angular, Vue, LoopBack, Express. Making the web awesome since 2002.