You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript(Angular)中如何使用async/await控制异步方法执行顺序

解决方法

你遇到的执行顺序问题核心原因是getLocation内部调用的navigator.geolocation.getCurrentPosition是回调式异步API,本身不会阻塞后续代码执行,所以天气接口会在定位结果返回前就触发。用async/await解决只需要两步:

第一步:把getLocation改造为返回Promise的异步函数

getLocation(): Promise<void> {
  return new Promise((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);
            // 定位成功后标记异步完成
            resolve();
          }
        },
        (error: PositionError) => {
          console.log(error);
          // 定位失败抛出异常
          reject(error);
        });
    } else {
      alert("Geolocation is not supported by this browser.");
      reject("当前浏览器不支持定位功能");
    }
  });
}

第二步:修改ngOnInit为异步函数,等待定位完成后再调用天气接口

async ngOnInit() {
  try {
    // 等待定位完成后再执行后续代码
    await this.getLocation();
    // 注意:此处要和你上面存储的变量名对应,你之前存的是this.lat、this.lng,不要写错成this.latitude、this.longitude
    this.getWeatherByCoordinates();
  } catch (err) {
    // 自定义定位失败的降级逻辑
    console.error('无法获取定位,天气信息加载失败:', err);
  }
}

补充说明

如果你希望getWeatherByCoordinates也可以被await控制,可以把内部的RxJS订阅改为Promise形式:

async getWeatherByCoordinates() { 
  try {
    const res = await this.weatherService.getWeatherByLatAndLong(this.lat,this.lng).toPromise();
    console.log('res',res);
  } catch (err) {
    console.error('天气接口请求失败:', err);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:45:00