'Control of flow in Typescript

I am trying to call a function which will retrieve data from a storage object.

I need to do this and assign the returned storage value before the next function is called, which also has a asyncrounus function. This is the first function call:

getUnits(){
    this.storage.get('units').then((val => {
          if (val != null){
            this.units = val;
            console.log("Settings.TS: #28 Got units : " + this.units);      
          }else{
            this.units = "metric";
            console.log("Settings.TS: #31 No saved units found, assigning metric.")
          }
          
        }));

The second block of code is called directly after the getUnits() above:

this.getUnits();
    console.log("WEaTHER.TS Getting City Weather...city / country = " + city + " / " + country);
    if (country != null || country != ""){
      city = city+","+country;
      console.log("WEATHER.TS: coutry code enterView, city = " + city + " and units: " + this.units);
    }
    //https://api.openweathermap.org/data/2.5/weather?q=Dublin&appid=4f91a3e665c56d59e4c7d9045d38e85a
    const weatherJSON = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&units="+ this.units + "&appid="+this.appid;
    console.log("WEATHER.TS Getting this API call : " + weatherJSON);
    return this.http.get(weatherJSON);

When the code is executed the control flow passes back and forth between both functions as they are asynchronous.

My question is there anyway I can guarantee function A executes completely before the block of close directly following it is executed?



Solution 1:[1]

With async functions, if you want to ensure function B is called ONLY after function A has completed execution, you call function B in the then block of function A. For example, in your case it would be something like this

getUnits(){
this.storage.get('units').then((val => {
  if (val != null){
    this.units = val;
    console.log("Settings.TS: #28 Got units : " + this.units);      
  }else{
    this.units = "metric";
    console.log("Settings.TS: #31 No saved units found, assigning metric.")
  }

  //Call the second function here
  
}));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Delwyn Pinto