This week, a teammate had to handle a strange phenomenon 🤔 occurring while using an Angular App.
I remind you that Angular uses an asynchronous mechanism.
So, when you use the Angular App, for example clicking 🖱️ the menu, an event is thrown 🚀 , then proceeded later.
Most of the time, everything is fine 👌.
The heck is when you are app handle some events very quickly 💨 and so occur before expected 😮.
So you may have a functional value of a previous call used instead of the one you are waiting for.
And you end with an incorrect ❌ GUI.
There are many ways 💡💡💡 of dealing with such a setting.
But when you deal with 𝐏𝐫𝐨𝐦𝐢𝐬𝐞 (https://lnkd.in/eJCwBNW2), you can just use the JS keyword 𝐚𝐰𝐚𝐢𝐭 before the call of your method returning a promise.
It will wait ⏱️ for the promise to return its result. YAY! ☺️
An outstanding, tremendous, snazzy gift from JavaScript. 💪
It made my day! 🙏 (I was investigating a complex fix with Angular change detection)
Example from stackoverflow:
getLocation() { //just line below the Promise return type return new 𝐏𝐫𝐨𝐦𝐢𝐬𝐞((resolve, reject) => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition((position: Position) => { if (position) { console.log("Latitude: " + position.coords.latitude + "Longitude: " + position.coords.longitude); this.lat = position.coords.latitude; this.lng = position.coords.longitude; console.log(this.lat); console.log(this.lng); resolve({ lat:position.coords.latitude, lng:position.coords.longitude }) } }, (error: PositionError) => reject(error)); } else { alert("Geolocation is not supported by this browser."); } }); } async ngOnInit() { 𝐚𝐰𝐚𝐢𝐭 this.getLocation();//here the await keyword this.getWeatherByCoordinates(); }
#angular #tip #angularProgramming #await