微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Typescript 中的流程控制

如何解决Typescript 中的流程控制

我正在尝试调用一个函数,该函数将从存储对象中检索数据。

我需要这样做并在调用一个函数之前分配返回的存储值,该函数也具有异步函数。这是第一个函数调用

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.")
          }
          
        }));

在上面的 getUnits() 之后直接调用第二块代码

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);

代码执行时,控制流在两个函数之间来回传递,因为它们是异步的。

我的问题是无论如何我可以保证函数 A 在紧随其后的 close 块执行之前完全执行吗?

解决方法

对于异步函数,如果您想确保仅在函数 A 执行完毕后才调用函数 B,您可以在函数 A 的 then 块中调用函数 B。例如,在您的情况下像这样

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
  
}));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。