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

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