【问题标题】:"is not a function" error ; Trying to user Geolocation API and weather API“不是函数”错误;尝试使用 Geolocation API 和 Weather API
【发布时间】:2020-12-25 03:15:17
【问题描述】:

我在通过天气 API 的异步获取函数传递用户位置时遇到问题。

代码

let lat = "48.8566";
let long = "2.3522";

  const fetchWeatherData = (async (lat, long) => {
    const response = await fetch(
      " http://api.weatherstack.com/current?access_key={API_KEY}query=" + lat + "," + long
    ).then(resp => resp.json()).then(
      function(apiResponse) {
       console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
     }
    );
    return await console.log(response.json());
  })();

  
function setUserLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(setPosition);
    console.log("click on button worked");
  } else { 
    alert("location api not supported by browser");
  }
}

function setPosition(position) {
  lat =  position.coords.latitude;
  long =  position.coords.longitude;
  fetchWeatherData.response(lat, long);
  console.log("Lat: " + lat + " and Long:"  + long);
}

我已尝试更改函数fetchWeatherData.response(lat, long);,但仍然无法绕过错误fetchWeatherData.response() is not a function at setPosition。我不确定我的错误是来自函数调用还是来自其他地方,例如async (lat, long) => ...

我能够获取用户位置,但是当我尝试在异步函数中传递新的 lat 和 long 作为参数时,我的问题就开始了。

有没有更好的方法来解决这个问题?

【问题讨论】:

    标签: javascript api asynchronous


    【解决方案1】:

    你有 .thenawait 的奇怪组合,尽量不要混合方法:

    let lat = "48.8566";
    let long = "2.3522";
    
    const fetchWeather = async (lat, long) => {
      const response = await fetch(
        " http://api.weatherstack.com/current?access_key={API_KEY}query=" + lat + "," + long
      )
      const apiResponse = await response.json();
      console.log(`Current temperature in ${apiResponse.location.name} is ${apiResponse.current.temperature}℃`);
      return data
    }
    
    function setUserLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setPosition);
        console.log("click on button worked");
      } else { 
        alert("location api not supported by browser");
      }
    }
    
    function setPosition(position) {
      lat = position.coords.latitude;
      long = position.coords.longitude;
      fetchWeather(lat, long);
      console.log("Lat: " + lat + " and Long:"  + long);
    }
    

    【讨论】:

    • 修复了一些其他问题,这很有效。这更有意义。这种方式允许更大的灵活性。非常感谢,因为这有助于我更多地了解我做错了什么。
    猜你喜欢
    • 1970-01-01
    • 2019-07-15
    • 2016-12-27
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多