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

270
Vistas
How to iterate using iterator over API object using JavaScript?

I want to iterate over a JSON object(array) through JavaScript iterator. I am not able to store the data fetched from the iterator function in a variable so that I can use the variable for DOM manipulation.

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};
        }
    };
}

Here I want to get the next array data stored to variable 'a' whenever a click event occurs. Please help.

P.S. I am still in the process of learning JavaScript.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You're calling getCV() which does repeat the request and create a new iterator every time you click the element. It sounds like what you actually want to do is

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
  });
});

or

getCV().then(iterator => {
  next.addEventListener('click', function nextCV(e) {
    const a = iterator.next().value
    console.log(a); // or DOM manipulation
  });
}).catch(console.error);
about 4 years ago · Juan Pablo Isaza Denunciar

0

I tried to simulate the fetch Promise and I think this is what you're looking for? Ofcourse there can be optimizations like avoid making the same API call and just return the cached result depending on the usecase.

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>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Thanks everyone for their valuable time.Here is how i got my final out.Hope this helps someone in future.

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};
        }
    };
}
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