I am learning to work with NodeJS and I came with a problem. getCurrentWeather() is asynchronous function which loads instantly when I start the app, and writes data to variables. When I use those variables outside the function to console.log() data, I get undefined results, because Node doesn't wait until getCurrentWeather() gets API data, it just executes code instantly while it still doesn't have anything to return. I solved it with another function renewCurrentWeather() and added setTimeout to wait while getCurrentWeather() gets data, and only then console.log() it.
This method works for me, but the problem is that if I want to use this data more than one time,I have to use the function wiht setTimeout. This looks to me a little buggy, because I need to use this data in more complex situations.
So my question is, how do I make Node.JS execute console.log(temp, cond) only then, when getCurrentWeather() fully finished loading data from API. In other words, I just want to use variables temp and cond everywhere in the app, without any funtions attached to it.
// Get weather data from Weather Underground every 3 minutes (due to daily 500 calls per day limit)
function getCurrentWeather() {
wunder.conditions('', function (err, data) {
if (err) throw err;
temp = data.temp_c;
cond = data.weather;
});
};
getCurrentWeather();
setInterval(getCurrentWeather, 180000);
// Use data recieved from API as much times as I need
function renewCurrentWeather() {
setTimeout(function() {
console.log(temp + " " + cond);
}, 1000);
};