Necesito recorrer los datos que que obtuve mediante fetch()
para así poder devolver el valor de un boleto de autobús, dependiendo de los km recorridos. En el archivo del fetch están los valores por km.
Este es mi código:
function cargarBoletos() {
fetch('boletos.json')
.then((res) => res.json())
.then((data) => {
console.log(data)
return data;
})
}
let valor = 0;
async function retornarValor(km, tarifa_social) {
let boleto = await cargarBoletos();
let i = 0;
while (i < 4) {
if (km <= boleto[i].km_max) {
if (tarifa_social == true) {
valor = boleto[i].tarifa;
} else { valor = boleto[i].pasaje; }
break;
}
i = i + 1;
}
if (km >= 28) {
if (tarifa_social == true) {
valor = 10.35;
} else { valor = 23 }
}
return valor;
}
Llamo a retornarValor
con otra función, donde hay una variable let valor_boleto = retornarValor(km, tarifa_social);
y de ahí creo un div que muestra los datos por pantalla.
El tema, es que me salta este error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0') at retornarValor
y en pantalla se muestra "El viaje te salió $[objet Promise]".
En la consola, en el objeto me sale:
valor_boleto: Promise
[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: TypeError: Cannot read properties of undefined (reading '0') at retornarValor
boletos[i]
esundefined
, y estas intentando leer propiedades (tarifa
,pasaje
) de un objeto indefinido