Estoy trabajando en una aplicación meteorológica que extrae algunos datos.
A la mitad deja de reconocer uno de los objetos como un objeto y arroja: Uncaught (in promise) TypeError: data is undefined
Ahora, esto parece estar relacionado con mi if anidado. Si elimino las líneas indicadas, funciona bien y la promesa se completa. De lo contrario arroja el error.
Este es el script que dejó de funcionar.
async function processHourly(hourly){ let data = await pullData(hourly); // Pull data is just fetch.then(return res.json) data = data.properties; let dataHours = data.periods; // Exception thrown on data, here. let weatherObj = new Array; let objNum=0; let avgTemp; let dateCheck; for(x in dataHours) { // Grab the day's hours //console.log(dataHours[x].startTime) if(dataHours[x].startTime.slice(8,10)!=dateCheck){ weatherObj[objNum] = new Weather weatherObj[objNum].Year = dataHours[x].startTime.slice(0,4) // takes 0-3 weatherObj[objNum].Month = dataHours[x].startTime.slice(5,7)-1 // takes 5 and 6 weatherObj[objNum].Date = dataHours[x].startTime.slice(8,10) // takes 8 and 9 weatherObj[objNum].getDay(); objNum++; typeof(weatherObj[objNum]) // If these are removed if(dataHours[x].startTime.slice(11,13)>=12) // Then it processes data as { // a completed promise. weatherObj[objNum].IsNight = true; // } // } dateCheck=dataHours[x].startTime.slice(8,10); } console.log(dataHours) for(x in weatherObj){ weatherObj[x].setDateObj() console.log(x,weatherObj[x].dateObj) } }¿Alguien sabe por qué es eso? Siento que me estoy perdiendo algo bastante simple. ¿No parece que las variables afecten el alcance de los datos?
editar -1/7/22, función pullData aclarada
Esta es una aplicación meteorológica simple que se reproducirá en una pantalla en bucle para la comunidad. Extrae datos de los pronósticos por hora de la API de weather.gov y procesa algunos datos. Este es el proceso que se está realizando.
El esquema json de data se puede encontrar aquí
Si bien no estoy completamente seguro de por qué, parece que usar = para asignar el valor estaba causando problemas en lugar de usar funciones de matriz.
El siguiente es un acortamiento del resaltado original donde radica mi problema.
if(dataHours[x].startTime.slice(8,10)!=dateCheck){ weatherObj[objNum] = new Weather /** THIS IS OUR PROBLEM CHILD **/ ... ... if(dataHours[x].startTime.slice(11,13)>=12) // Then it processes data as { // a completed promise. weatherObj[objNum].IsNight = true; // } // }En su lugar, usé .push() para asignar el nuevo objeto meteorológico al lugar. Seguimiento mediante la asignación de objNum para igualar el índice del objeto meteorológico actual a medida que itera a través de la creación.
Además, agregué claves para la hora del pronóstico para su posterior procesamiento y promedio.
La corrección con la que terminé es la siguiente.
let checkable; //Good for testing async function processHourly(hourly) { let data = await pullData(hourly); data = data.properties; let dataHours = data.periods; let weatherObj = new Array; let objNum=0; let dateCheck=-1; // forces first pass to always create a new weather console.log(dataHours[0]) // To double check variable names for(x in dataHours){ // Start creating objects if( dataHours[x].startTime.slice(8,10)!=dateCheck){ weatherObj.push(new Weather); dateCheck = dataHours[x].startTime.slice(8,10); objNum = weatherObj.length-1 } weatherObj[objNum].hourTemp.push({ hour : dataHours[x].startTime.slice(11,13), temp : dataHours[x].temperature }); weatherObj[objNum].hourForecast.push({ hour : dataHours[x].startTime.slice(11,13), forecast : dataHours[x].shortForecast }) weatherObj[objNum].hourWindDir.push({ hour : dataHours[x].startTime.slice(11,13), direction : dataHours[x].windDirection }) weatherObj[objNum].hourWindspeed.push({ hour : dataHours[x].startTime.slice(11,13), speed : dataHours[x].windSpeed.slice(0,-4) }) } checkable = weatherObj }