I am working on a simple weather application which uses mysql database that has just the names of the cities. Than i query the database for all the names and i send request to openweathermap's API for the weather info.
function getCities() {
con.connect();
con.query(('SELECT city_name FROM cities'), (err, res) => {
console.log(res);
getWeather(cities);
});
};
async function getWeather(cities) {
var data = [];
for (var i = 0; i < cities.length; i++) {
var url = `http://api.openweathermap.org/data/2.5/weather?q=${cities[i].city_name}&units=metric&appid=271d1234d3f497eed5b1d80a07b3fcd1`;
await request(url, (err, res, body) => {
var json = JSON.parse(body);
var weather = {
city: json.name,
temperature: json.main.temp,
description: json.weather[0].description,
icon: json.weather[0].icon
};
data.push(weather);
});
}
console.log(data);
}
The getCities() function works as expected and returns all the cities but the errors happen in the getWeather function particulary these errors:
Desktop/WeatherApp/node_modules/request-promise-core/lib/plumbing.js:130
throw thrownException;
^
TypeError: Cannot read property 'temp' of undefined
at Request.request [as _rp_callbackOrig] (/home/kristijan/Desktop/WeatherApp/app.js:60:41)
at Request.plumbing.callback (/home/kristijan/Desktop/WeatherApp/node_modules/request-promise-core/lib/plumbing.js:76:39)
at Request.RP$callback [as _callback] (/home/kristijan/Desktop/WeatherApp/node_modules/request-promise-core/lib/plumbing.js:46:31)
at Request.self.callback (/home/kristijan/Desktop/WeatherApp/node_modules/request/request.js:185:22)
at Request.emit (events.js:182:13)
at Request.<anonymous> (/home/kristijan/Desktop/WeatherApp/node_modules/request/request.js:1161:10)
at Request.emit (events.js:182:13)
at IncomingMessage.<anonymous> (/home/kristijan/Desktop/WeatherApp/node_modules/request/request.js:1083:12)
at Object.onceWrapper (events.js:273:13)
at IncomingMessage.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
As far as i understood it is jumping the inside of the arrow function before getting the result from the API ?
requestdoes not return a promise, so yourawaitdoes nothing. You need to actually use promises.getCities()because if that is actually creating the connection to your MySQL instance, that's a very expensive call that could fail sometimes--it would be better to hold the connection as a singleton or just a member variable in the local context