So I want to require this function from another file and use it in main.js. But I keep getting undefined
. Now that doesn't surprise me. Because with console.log
I see prepareWeather()
has finished before getWeather()
has finished. But it also stays empty/undefined.
The function needs to update the variable globalWeather
every 15 minutes in main.js. So it's updated with the latest weather info.
I tried everything with async/await and .next() but I have absolutley no idea what I'm doing anymore. I feel pretty lost.
I stripped the code down to only the necessary to make it readable. That's also the reason I want getWeather()
to be in a separate file. It is pretty long.
Can someone tell me how to make this work? And furthermore, explain me why this doesn't work?
main.js
const getWeather = require("./functions/getweather.js");
let globalWeather = {};
prepareWeather();
async function prepareWeather() {
console.log(`a: ${Date.now()}`);
globalWeather = await getWeather(); //return object
console.log(`b: ${Date.now()}`);
console.log(globalWeather);
console.log(`c ${Date.now()}`);
setTimeout(prepareWeather, 10000); //900000 when it works
}
getweather.js
module.exports = exports = async function getWeather(){
const request = require("request");
const key = `XXX`;
const lat = `10.01`;
const lon = `10.01`;
const units = `metric`;
let url = `http://api.openweathermap.org/data/2.5/weather`+
`?APPID=`+key+
`&lat=`+lat+
`&lon=`+lon+
`&units=`+units;
console.log(`1 ${Date.now()}`);
await request({
url: url,
json: true
}, await function (error, response, body) {
console.log(`2 ${Date.now()}`);
if (!error && response.statusCode === 200) {
console.log(`3 ${Date.now()}`);
let wobj = body;
let id = wobj.weather[0].id;
if (id === 200 || id === 201) {
wobj.emoji = `⛈`;
} else if(id === 300) {
wobj.emoji = ``;
}
console.log(`4 ${Date.now()}`)
//console.log(wobj);
return wobj;
}
});
}
console:
a: 1520974253102
1 1520974253103
b: 1520974253125
undefined //This is console.log(globalWeather);
c 1520974253125
2 1520974253159
3 1520974253159
4 1520974253159
//console.log(wobj);
in getweather.js does eventually return an object in my console. But not in main.js.