You need to enable JavaScript to run this app. TypeScript 异步流程控制:如何保证Storage读取函数执行完成后再运行后续代码
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript 异步流程控制:如何保证Storage读取函数执行完成后再运行后续代码

确保异步逻辑按顺序执行的实现方案

核心问题根源

当前getUnits方法没有把内部storage.get返回的Promise向外透传,调用this.getUnits()时,方法会立刻返回undefined,完全不会等存储读取的异步操作执行完成,直接跳去跑后续代码,这才导致this.units还没赋值,天气请求的URL就已经拼接完成了。

改造步骤

1. 重构getUnits方法,透传异步Promise

去掉内部对Promise链路的截断,把最外层的Promise直接返回,让外部可以接收到存储读取完成的通知:

getUnits(){
  // 直接返回storage.get生成的Promise,透传整个异步链路
  return 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.")
    }
  });
}

关键改动:在this.storage.get前加return,让方法返回值和内部异步流程绑定。

2. 串联后续业务逻辑,等异步赋值完成再执行请求

确保this.units拿到赋值结果后,再拼接请求URL、发起天气接口调用,有两种常用实现方式:

  • 方式1:Promise链式调用
this.getUnits().then(() => {
  console.log("WEATHER.TS Getting City Weather...city / country = " + city + " / " + country);
  if (country != null || country != ""){
    city = city + "," + country;
    console.log("WEATHER.TS: country code enterView, city = " + city + " and units: " + this.units);
  }
  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);
});
  • 方式2:async/await写法
    如果当前所在方法可以标记为async,可以用更贴近同步书写习惯的写法:
// 标记当前业务方法为async
async loadCityWeather(city: string, country: string) {
  // 暂停后续代码执行,直到getUnits内部的存储读取、赋值逻辑全部完成
  await this.getUnits();
  console.log("WEATHER.TS Getting City Weather...city / country = " + city + " / " + country);
  if (country != null || country != ""){
    city = city + "," + country;
    console.log("WEATHER.TS: country code enterView, city = " + city + " and units: " + this.units);
  }
  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);
}

注意:被标记为async的方法会自动返回Promise,和原代码直接返回HTTP请求的行为完全兼容,不会破坏原有调用链路的使用方式。

内容的提问来源于stack exchange,提问作者dancingbush

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 08:36:04