0

I'm building a time and weather app. I have two functions. showtime() that awaits getWeather(). The constants log fine in getWeather(), but when I try to retrieve the same constant in showtime() I get undefined... 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.
Drax
  • 169
  • 1
  • 8
  • Just `return` the value from the function, and assign it to a local variable in the scope of the call. – Bergi Apr 08 '20 at 12:40

1 Answers1

1

This is because of the variable scoping.

You declared the variable sunrisetime inside the function scope of getWeather

So, it can not be called in the 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);

}


Read more about variable hoisting in JS Here

Ahmed Gaafer
  • 1,603
  • 9
  • 26