【问题标题】:keep getting empty result on my previous promise我之前的承诺不断得到空洞的结果
【发布时间】:2020-08-07 13:55:06
【问题描述】:
    this.state = {
      city: null,
      cityNumber : null,
      typeWeather: "",
      minTemp: 0,
      maxTemp: 0,
      theTemp: 0
    };
  }


  SearchingCity = (city) => {
    return new Promise(resolve => {
      axios.get(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/search/?query=${city}`)
      .then((result) => {
        let cityName = result.data[0].woeid;
            this.setState({
              city: cityName
            });
            resolve(cityName)
      })
    })
  }

  getCityID = async () => {
    const cityID = await this.SearchingCity();
    console.log(cityID)
    this.setState({
      cityNumber : cityID
    })
    const thisID = this.state.cityNumber;
    axios.get(`https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/${thisID}`)
    .then((result) => {
      const type_Weather = result.data.consolidated_weather[0].weather_state_name
      const min_Temp = result.data.consolidated_weather[0].min_temp
      const max_Temp = result.data.consolidated_weather[0].max_temp
      const the_Temp = result.data.consolidated_weather[0].the_temp

      this.setState({
        typeWeather : type_Weather,
        minTemp : min_Temp,
        maxTemp : max_Temp,
        theTemp : the_Temp
      })
    })
  }

所以在 console.log(cityID) 中它应该是 SearchingCity 方法的结果,但是 当我 console.log(cityID) 时,我得到了空结果,我应该改变的部分在哪里?

谢谢大家

【问题讨论】:

  • 可能是因为您没有将任何城市传递给该方法? const cityID = await this.SearchingCity(CITY_YOU_WANT);

标签: javascript reactjs api axios


【解决方案1】:

正如 @gbalduzzi 指出的那样, 问题来了,

const cityID = await this.SearchingCity();
//                                     ^^

您没有根据需要使用任何city 参数调用SearchingCity

  SearchingCity = (city) => {
//                ^^^^^^

【讨论】:

    猜你喜欢
    • 2016-08-13
    • 2019-02-10
    • 2021-08-15
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 2016-12-10
    相关资源
    最近更新 更多