Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda