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

188
Vistas
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 Respuestas
Responde la pregunta

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