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

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

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