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

如何让变量等待Weather类getWeather方法内的fetch请求结果?

问题:调用Weather类的getWeather方法返回undefined

我创建了一个Weather类,用于从OpenWeather API获取地理天气信息。在Angular组件中调用.getWeather(cityName)方法时,该方法会先获取城市坐标,再发起另一个fetch请求获取对应城市的天气数据,最后将数据传入displayCurrentWeather方法格式化。但在组件类中调用getWeather()并赋值给变量时,得到的结果是undefined。我觉得这是Promise相关的问题,但试了多种async/await写法都没解决。

Weather类代码

export class Weather {
  static displayCurrentWeather(data: {
    temp: number;
    feels_like: number;
    temp_min: number;
    temp_max: number;
    pressure: number;
    humidity: number;
  }) {
    return data;
  }

  static fetchWeatherByCoordinates(coords: {
    latitude: number;
    longitude: number;
  }) {
    fetch(
      `https://api.openweathermap.org/data/2.5/weather?lat=${coords.latitude}&lon=${coords.longitude}&units=imperial&appid=${apikey}`
    )
      .then(function (response) {
        return response.json();
      })
      .then(function (data) {
        console.log(data.main);
        console.log(data.weather);
        Weather.displayCurrentWeather(data.main);
      });
  }

  getWeather(cityName: string) {
    let coords;
    fetch(
      `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${key}`
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        coords = {
          latitude: data[0].lat,
          longitude: data[0].lon,
        };
        Weather.fetchWeatherByCoordinates(coords);
      });
  }
}

组件调用代码

export class SearchBar {
  inputValue: string = '';

  fetchWeather() {
    const weather = new Weather();
    let data = weather.getWeather(this.inputValue);  // <---- Data comes back undefined
    console.log('Data ' + data);
  }
}

问题根源

你的getWeather和fetchWeatherByCoordinates方法都没有返回Promise对象,且内部异步操作的结果没有正确向上传递,导致上层调用无法获取到异步请求的最终数据。

修复步骤

1. 让fetchWeatherByCoordinates返回Promise并传递数据

修改静态方法,返回fetch的Promise链,并在最后返回格式化后的天气数据:

static fetchWeatherByCoordinates(coords: {
  latitude: number;
  longitude: number;
}): Promise<{
  temp: number;
  feels_like: number;
  temp_min: number;
  temp_max: number;
  pressure: number;
  humidity: number;
}> {
  return fetch(
    `https://api.openweathermap.org/data/2.5/weather?lat=${coords.latitude}&lon=${coords.longitude}&units=imperial&appid=${apikey}`
  )
    .then(response => response.json())
    .then(data => {
      console.log(data.main);
      console.log(data.weather);
      return Weather.displayCurrentWeather(data.main); // 返回格式化后的数据
    });
}

2. 让getWeather返回Promise并串联异步操作

修改getWeather方法,返回Promise链,确保坐标查询完成后,将天气请求的结果向上传递:

getWeather(cityName: string): Promise<{
  temp: number;
  feels_like: number;
  temp_min: number;
  temp_max: number;
  pressure: number;
  humidity: number;
}> {
  return fetch(
    `https://api.openweathermap.org/geo/1.0/direct?q=${cityName}&limit=1&appid=${key}`
  )
    .then(response => response.json())
    .then(data => {
      const coords = {
        latitude: data[0].lat,
        longitude: data[0].lon,
      };
      return Weather.fetchWeatherByCoordinates(coords); // 返回天气请求的Promise
    });
}

3. 在组件中用异步方式处理结果

因为getWeather现在返回Promise,组件需要用async/await或.then来获取数据:

export class SearchBar {
  inputValue: string = '';

  // 用async/await写法
  async fetchWeather() {
    const weather = new Weather();
    try {
      const data = await weather.getWeather(this.inputValue);
      console.log('Data:', data); // 现在能拿到正确数据
    } catch (error) {
      console.error('获取天气失败:', error);
    }
  }

  // 或者用.then链式调用写法
  // fetchWeather() {
  //   const weather = new Weather();
  //   weather.getWeather(this.inputValue)
  //     .then(data => {
  //       console.log('Data:', data);
  //     })
  //     .catch(error => {
  //       console.error('获取天气失败:', error);
  //     });
  // }
}

关键说明

  • 异步操作(比如fetch)本身返回Promise,必须返回这个Promise链,上层才能获取到异步结果。
  • 所有需要传递结果的.then回调中,都要return对应的数据或Promise,否则异步链会断裂,上层拿不到值。
  • Angular中处理异步操作时,async/await能让代码更易读,同时必须用try/catch处理请求异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 01:50:13