Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
El bucle FOR OF a través de los datos de respuesta de mi API no muestra ningún resultado. (mi intento local funciona)

Es la primera vez que trabajo con una API. He pegado mi código a continuación con algunos comentarios sobre lo que estoy tratando de lograr con él y si mis pequeñas pruebas en el camino funcionan o fallan.

La primera parte es lo que se supone que debo hacer. La segunda mitad es una prueba que implementé para ver si mi lógica de loop+display es inestable. No parece ser el problema. Mi teoría de trabajo es que estoy fallando en la 'entrega' de los datos que obtuve en algún momento.

¿Puedes ver dónde hice algo mal u olvidé algo?

 async function getCatalog() { //storing response let response = await fetch(apiURL); // stars a GET request (default) // Storing data in form of JSON const catalog = await response.json(); console.log(catalog, typeof catalog); // TESTS: these work. I recieve the expected information if (response) { //return catalog; // I'm not sure if I need this or not to make displayCatalog work. displayCatalog(); } } //calling async function getCatalog(); //TEST document.getElementById('items').style.border = '1px dashed blue'; // this is the target element in my HTML where I want to display my results. I gave it a border to be able to see it while I work. // function to define innerHTML function displayCatalog() { //Here I am trying to loop through the objects in my response to display some of the information. Before I focus on displaying the right info correctly, I'm trying to display ANY of it. for (let item of catalog) { let newDiv = document.createElement('div'); let newContent = `Hello I'm ${item.name}`; newDiv.innerHTML = newContent; newDiv.style.border = '2px dashed red'; document.getElementById('items').appendChild(newDiv); } } // NO API TEST // Here I created an array with a few objects in it to loop through it and see if my logic is sound there. It does work. It displays what I expect it to. let objArray = [ { name: 'Dean', species: 'Human(ish)', eyecolor: 'Green', car: 'Baby, duh', }, { name: 'Sam', species: 'Human', eyecolor: 'Hazel', status: 'Alive', car: 'green', }, { name: 'Castiel', species: 'Human(ish)', eyecolor: 'Blue', bonded: 'yes', car: 'black', }, ]; let attempt; for (let item of objArray) { let Bap = document.createElement('div'); attempt = `Hi, my name is ${item.name}, my car is ${item.car}.`; Bap.innerHTML = attempt; Bap.style.border = '1px dashed green'; document.getElementById('items').appendChild(Bap); }```
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

el problema es que está definiendo catalog dentro getCatalog e intenta usarlo dentro displayCatalog (donde no está definido)

En cambio, deberías hacerlo de esta manera.

 function displayCatalog(catalog){ ... }

y pasar el catálogo al llamar a la función

 async function getCatalog() { let response = await fetch(apiURL); // stars a GET request (default) const catalog = await response.json(); if (response) { displayCatalog(catalog); } }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Creo que catalog es una variable local de la función getCatalog y, por lo tanto, no se puede usar dentro de la función displayCatalog.

Puede pasarlo como argumento al llamar a la función:

 async function getCatalog() { ... if (response) { displayCatalog(catalog); } } function displayCatalog(catalog) { ... //the variable catalog is now accessible }

Alternativamente, si llamaste al catálogo de parámetros de otra forma en la definición de la función para displayCatalog() como la function displayCatalog(info) , ahora sería accesible como la información de la variable local.

Tenga en cuenta que devolver el catálogo desde getCatalog terminaría esa función.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda