Quiero iterar sobre un objeto JSON (matriz) a través del iterador de JavaScript. No puedo almacenar los datos obtenidos de la función de iterador en una variable para poder usar la variable para la manipulación de DOM.
next.addEventListener('click',nextCV); function nextCV(){ const a =getCV().then(data=> data.next().value) } function getCV(){ return fetch(url).then(response=>{return response.json() }).then(data=>{ return iteratorCV(data.results) }) } function iteratorCV(data){ console.log('inside iterator') let nextindex=0; return { next: function(){ return nextindex<data.length ? {value: data[nextindex++], done:false} : {done:true}; } }; }Aquí quiero obtener la siguiente matriz de datos almacenada en la variable 'a' siempre que ocurra un evento de clic. Por favor ayuda.
PD: todavía estoy en el proceso de aprender JavaScript.
Está llamando a getCV() , que repite la solicitud y crea un nuevo iterador cada vez que hace clic en el elemento. Parece que lo que realmente quieres hacer es
const iteratorPromise = getCV(); iteratorPromise.catch(console.error); next.addEventListener('click', function nextCV(e) { iteratorPromise.then(iterator => { const a = iterator.next().value; console.log(a); // or DOM manipulation }); });o
getCV().then(iterator => { next.addEventListener('click', function nextCV(e) { const a = iterator.next().value console.log(a); // or DOM manipulation }); }).catch(console.error);Traté de simular la Promesa de fetch y creo que esto es lo que estás buscando. Por supuesto, puede haber optimizaciones como evitar hacer la misma llamada API y simplemente devolver el resultado almacenado en cached según el caso de uso.
const btn = document.querySelector('button'); btn.addEventListener('click',nextCV); async function nextCV(){ let it = await getCV(); let result = it.next(); const a = []; while(!result.done) { a.push(result.value) result = it.next(); } // Result stores in 'a'. Do DOM manipulation from here console.log('final result', a); } function getCV(){ return new Promise((resolve) => { setTimeout(() => { resolve(iteratorCV([1,2,3,4,5])) }, 1000) }) } function iteratorCV(data){ console.log('inside iterator') let nextindex=0; return { next: function(){ return nextindex<data.length ? {value: data[nextindex++], done:false} : {done:true}; } }; } <button> Click </button>Gracias a todos por su valioso tiempo. Así es como obtuve mi salida final. Espero que esto ayude a alguien en el futuro.
const url="https://......."; //adding button for the iteration const next = document.getElementById('next'); //for Dom manipulation let image=document.getElementById('image'); let profile=document.getElementById('profile'); getCV().then(iterator => { next.addEventListener('click', function nextCV(e) { const a = iterator.next().value console.log(a); //now you can use the variable for DOM manipulation image.innerHTML= }); }) //get api function getCV(){ return fetch(url).then(response=>{ return response.json() }).then(data=>{ console.log(data.results) return iteratorCV(data.results); }) } //Iterating over the FETCHED DATA one by one data function iteratorCV(data){ console.log('inside iterator') // console.log(data) let nextindex=0; return { next: function(){ return nextindex<data.length ? {value: data[nextindex++], done:false} : {done:true}; } }; }