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

131
Views
Extracting value from promise after .then function

I have an asynchronous API call that returns a promise containing the username of the currently logged in user. I am able to extract the username by using the .then function. However, when I try to access the username from outside the .then function, I always get "undefined."

  const getUsername = async () => {
    try {
      const res = await fetch("http://localhost:1234/username", {
        method: "POST",
        headers: { jwt_token: localStorage.token }
      });

      const parseRes = await res.json();
      return parseRes;
    } catch (err) {
      console.error(err.message);
    }
  }

  var username;
  function setUsername(uname) {
    username = uname;
  }

  const p = getUsername();
  p.then(value => {
    setUsername(value.username);
  });

  console.log(username); // returns "undefined"

I have tried doing this in multiple ways such as: directly assigning to the username variable, writing a function to set the username variable (as shown in this example), and putting my return function (for the react component) inside my .then function, which bricks the whole app.

How would I go about retrieving the result of this API call?

about 4 years ago · Juan Pablo Isaza
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!