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

187
Visualizações
How to access variable inside a for-in loop within an async function (javascript/react)?

So I made this little fetch function in a React project to loop through the returned object and give me a number of something.
I'm trying to get back the value of profileCount to access it outside of the async function.
How would I do that?

useEffect(() => {
  async function getProfiles() {
    try {
      const url = '';

      let h = new Headers();
      h.append('Accept', 'application/json');

      let encoded = window.btoa('superuser:superuser');
      let auth = 'Basic ' + encoded;

      h.append('Authorization', auth);

      const response = await fetch(url, {
        method: 'GET',
        mode: 'cors',
        headers: h,
        credentials: 'same-origin',
      });
      const data = await response.json();

      let results = data.results;
      let profileCount = 0;

      for (let key in results) {
        let innerObject = results[key];
        for (let newKey in innerObject) {
          if (innerObject[newKey].indexOf('pages/ProfilePage') > -1) {
            profileCount += 1;
            return profileCount;
          }
        }
      }
    } catch (err) {
      console.log('test' + err);
    }
  }
  getProfiles();
}, []);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your code is good, just relocate the return statement after the for.

      for (let key in results) {
        let innerObject = results[key];
        for (let newKey in innerObject) {
          if (innerObject[newKey].indexOf('pages/ProfilePage') > -1) {
            profileCount += 1;
          }
        }
      }

      return profileCount;

The workflow is the following,

useEffect(async () => {
  async function getProfiles() {}
  const count = await getProfiles();
}, []);

But you might have to do this to avoid warning,

    useEffect(() => {
      (async () => {
        let response = await fetch('api/data')
      })();
    }, [])
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