首页 > 解决方案 > 创建类以获取天气

问题描述

请帮忙,我创建了主类来获取四天的天气,但控制台抛出错误 - 未定义 getCoordinates。问题是什么?还是函数init错了?我有函数 getCoordinates,而不是获取城市并返回纬度和经度,然后应该将它传递给函数 get WeatherForeCast 以获取天气,然后从该函数将数据传递给函数 renderForeCastInfo 以获取四天的天气。怎么了?

class Weather {

    async getCoordinates() {
        //code
    }

    async getWeatherForecast(locationCoordinates) {
        //code
      }

    fahrenheitToCelsius(temp) {
        //code
    }

    renderForecastInfo(currently, daily) {
         //code
    }

    init() {
        getCoordinates().then(coords => {
            return getWeatherForecast(coords);
        }).then((forecast) => {
            const { currently, daily } = forecast;
            renderForecastInfo(currently, daily);
        });
    }
}

标签: javascriptclassasynchronouspromise

解决方案


您必须参考this成员函数。请看下面的代码。

class Weather {
    constructor(city) {
        this.city = city
    }

    async getCoordinates(city) {
         //code
    }

    async getWeatherForecast(locationCoordinates) {
         //code
      }

    fahrenheitToCelsius(temp) {
         //code
    }

    renderForecastInfo(currently, daily) {
         //code
    }

    init() {
    
        this.getCoordinates().then(coords => {
            return this.getWeatherForecast(coords);
        }).then((forecast) => {
            const { currently, daily } = forecast;
            this.renderForecastInfo(currently, daily);
        });
    }
}
const w1= new Weather();
w1.init();


推荐阅读