JavaScript 全局变量赋值问题

JavaScript issue with global variable assignment

我正在尝试使用以下代码片段创建一个天气小部件。但是,全局变量经度和纬度值未在成功函数中更新。我已经尝试了 globalThis 和 window 对象的所有组合,但仍无法解决问题。

setInterval(showWeather, 900000);
setTimeout(showWeather,1000)

function showWeather(){
    var appid = "API_KEY_FOR_OPENWEATHERMAP";
    var latitude = 0;
    var longitude = 0;
        
    function success(position){
        window.latitude = position.coords.latitude;
        window.longitude = position.coords.longitude;
    }

    function error(){
        console.log('Some error occurred while retrieving your device location! Hence showing the default location weather!')
    }

    if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(success, error);
    }else{
        console.log("Your device doesn't support geolcation tracking! Hence showing the default location weather!")
    }
    
    async function fetchWeather(){
        var url = `https://api.openweathermap.org/data/2.5/weather?lat=${window.latitude}&lon=${window.longitude}&appid=${appid}&units=metric`
        const response = await fetch(url);
        data = response.json();
        return data
    }

    fetchWeather().then(response=>{
        const icon = response.weather[0].icon;
        document.getElementById("city").innerHTML = response.name;
        document.getElementById("temp").innerHTML = response.main.temp + "°";
        url = `https://openweathermap.org/img/w/${icon}.png`;
        document.getElementById("wicon").src = url;
    })
}
<h5 id="city">User Location</h5>
<div>
  <img id="wicon" src="https://openweathermap.org/img/w/01d.png" alt="Weather icon">
  <strong id="temp">Temperature&deg;</strong>
</div>

getCurrentPosition() 是异步的,但您无需等待它完成就可以使用结果。您应该从 success() 函数中调用 fetchWeather(),因为它是在 getCurrentPosition() 完成时调用的。

latitudelongitude 不需要使用全局变量。将它们作为参数传递给 fetchWeather().

setInterval(showWeather, 900000);
setTimeout(showWeather, 1000)

function showWeather() {
  var appid = "API_KEY_FOR_OPENWEATHERMAP";

  function success(position) {
    let latitude = position.coords.latitude;
    let longitude = position.coords.longitude;
    fetchWeather(latitude, longitude).then(response => {
      const icon = response.weather[0].icon;
      document.getElementById("city").innerHTML = response.name;
      document.getElementById("temp").innerHTML = response.main.temp + "&deg;";
      url = `https://openweathermap.org/img/w/${icon}.png`;
      document.getElementById("wicon").src = url;
    })
  }

  function error() {
    console.log('Some error occurred while retrieving your device location! Hence showing the default location weather!')
  }

  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error);
  } else {
    console.log("Your device doesn't support geolcation tracking! Hence showing the default location weather!")
  }

  async function fetchWeather(latitude, longitude) {
    var url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${appid}&units=metric`
    const response = await fetch(url);
    data = response.json();
    return data
  }
}
<h5 id="city">User Location</h5>
<div>
  <img id="wicon" src="https://openweathermap.org/img/w/01d.png" alt="Weather icon">
  <strong id="temp">Temperature&deg;</strong>
</div>