Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

269
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda