Been coding in JavaScript for about a year but I have this weird error/bug I have found a work around solution, but am curious on an explanation as to why.
So I have an asynchronous function receiving weather data from an API getWeatherStats() It returns a promise which is opened with the .then notation in another function called getCoordinates(). I simplified the weatherParser() function to show that if I make the solution recursive, it returns undefined, but if done iteratively it works fine.
getWeatherStats(city).then((data) => {
console.log(data)
var i = 0;
var done = weatherParser(data, i);
console.log(done); //returns undefined if done recursively, is fine if done iteratively
})
async function getWeatherStats(city) {
var url = `http://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${weatherKey}`;
let response = await fetch(url);
let data = await response.json();
var i = 0;
return new Promise(resolve => {
resolve(data);
}, 2000);
Here's the recursive solution that returns null
function weatherParser(data, i, widgetHolder, date = null) {
if (i > 20) return 'hello'
i++;
weatherParser(data, i, widgetHolder, date)
Iterative solution:
function weatherParser(data, i, widgetHolder, date = null) {
for (var i = 0; i < 20; i++) {
}
return 'hello'