Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
¿Cómo acceder a la variable dentro de un bucle for-in dentro de una función asíncrona (javascript/react)?

Así que hice esta pequeña función de búsqueda en un proyecto de React para recorrer el objeto devuelto y darme un número de algo.
Estoy tratando de recuperar el valor de profileCount para acceder a él fuera de la función asíncrona.
¿Como podría hacerlo?

 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 answers
Answer question

0

Su código es bueno, simplemente reubique la declaración de return después de 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;

El flujo de trabajo es el siguiente,

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

Pero puede que tenga que hacer esto para evitar la advertencia,

 useEffect(() => { (async () => { let response = await fetch('api/data') })(); }, [])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!