In my ngOnInit page I call a function to present a Loading and then call my service to load data.
The problem is that the service call ends before the loading starts.
How is it possibile with await?
Or don’t use async / await in the first place. I think they obscure what is really going on, which can be especially troubling for people getting used to asynchronous programming in general. I think it’s much better in the long run to train yourself to think and write reactively, instead of relying on syntax sugar to perpetuate imperative programming styles that are out-of-place for web apps.
I know the solution is to use a Promise and put everything inside the then() but I wanted to understand how it works and why it doesn’t work with async
Press the “win” button, you should see the loading indicator appear, sit there for a couple of seconds, disappear, and the result should be displayed as “won”. Press the “lose” button, the loading indicator should appear, disappear, be replaced by an alert, and the result should be displayed as “failed”.
Things to note:
no async / await
no any
no storing transient objects in controller properties (your loading). it becomes very difficult glancing at the code to know who is responsible for managing this object’s lifecycle, and if you mess that up, you end up with resource leaks or triggering double-dispose bugs
finalize operator allows centralizing instead of duplicating tear-down code