【问题标题】:error - function is not the function in child class错误 - 函数不是子类中的函数
【发布时间】:2020-08-22 17:24:12
【问题描述】:

我有一个父类 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']);

【问题讨论】:

  • makeRandom 不是异步函数,then 不需要,then 用于promise。
  • @BerkKurkcuoglu 如何将城市值传递给函数 getCoordinates?
  • this.getCoordinates(this.makeRandom())

标签: javascript arrays class asynchronous promise


【解决方案1】:

原因是makeRandom 没有返回承诺。如果您选择将其设为async 函数,则需要在getCoordinates 之前放置一个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);

});

【讨论】:

    猜你喜欢
    • 2020-04-17
    • 1970-01-01
    • 2016-02-26
    • 2013-04-01
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多