首页 > 解决方案 > 错误 - 函数不是子类中的函数

问题描述

我有一个父类 Weather,它显示了 4 天的天气。我有一个子类,其中包含一系列城市。他应该在这个数组中显示一个随机城市的 4 天的天气。但我有一个错误 - this.makeRandom(...).then 不是函数。怎么了?

class GetRandomCity extends Weather {
    constructor(city) {
        super();
        this.city = city;
    }

    makeRandom() {
       //code
    };

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

const w1 = new GetRandomCity(['Paris', 'Minsk', 'Madrid', 'Chikago']);

标签: javascriptarraysclassasynchronouspromise

解决方案


原因是因为makeRandom不返回承诺。getCoordinates如果您选择使其成为async函数,则需要在之前放置一个 return 语句。否则,您可以将init函数中的代码更改为此,它应该可以工作:

const city = this.makeRandom();

this.getCoordinates(city).then(coords => {

  return this.getWeatherForecast(coords);

}).then(forecast => {

  const { currently, daily } = forecast;
  this.renderForecastInfo(currently, daily);

});

推荐阅读