首页 > 解决方案 > 等待 OpenWeather 函数,然后运行另一个函数

问题描述

我正在构建一个时间和天气应用程序。我有两个功能。等待 getWeather() 的 showtime()。常量在 getWeather() 中记录正常,但是当我尝试在 showtime() 中检索相同的常量时,我​​得到未定义的... Fiddle

<div class="weekday"></div>

const weekday = document.querySelector('.weekday');
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur','Fri', 'Sat', 'Sun'];

setInterval(() => {
const d = new Date();
const day = days[d.getDay()];

    async function showtime() {
    await getWeather();
    console.log(sunriseTime); // returns undefined
    console.log(day) // logs fine, returns Wednesday. 
        weekday.innerHTML = day + ', Sunrise at: ' + sunriseTime;
    }
    showtime();
}, 1000);

// 

const openweather_api = "https://api.openweathermap.org/exampleexample";

async function getWeather() {
    console.log('run weather function first')
    const response = await fetch(openweather_api);  
    const json = await response.json();

    const sunriseTime = `${json.sys.sunrise}` // logs sunrise time in seconds. 
    }

getWeather(); // runs fine and retrieves values from Open Weather Json.

标签: javascript

解决方案


这是因为变量范围。

您在getWeather的函数范围内声明了变量sunrisetime

所以,不能在outerscope中调用


const b = 2;
console.log(a);// undefined because it is not declared in this scope

const foo = () => {
   const a = 1;

   console.log(a);// 1
   console.log(b);// 2

}

/*************************************************************************/
// a solution to this problem can be
let c;

const getInnerVariable = VAR => {
   return VAR;
}

const foo = () => {
   const a = 1;

   console.log(a);// 1
  c =  getIneerVariable(a);

}


在此处阅读有关 JS 中的变量提升的更多信息


推荐阅读