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

185
Visualizações
variable value not changing inside axios then method
let found = false;
axios
   .get(link)
   .then((response) => {
      response.data.map((element) => {
         if (element.id_ticket.toString() === nbTicket) found = true;
      });
      console.log(found);
   });

so im trying to get data from the api and see if the value of 'nbTicket' is in the returned data and that is done using the 'found' variable so if i log the 'found' variable value outside the .then method it stays false even if the value exists and when i do it iside the .then methods it gives the correct value

let found = false;
axios
   .get(link)
   .then((response) => {
      response.data.map((element) => {
         if (element.id_ticket.toString() === nbTicket) found = true;
      });
   });
   console.log(found);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

your console.log(found); is executing is executing before you fetch data from api you can call it inside then or use async await if you want to call console.log(found); after you get data from api

about 4 years ago · Juan Pablo Isaza Relatório

0

Your supposed to use async/await strategy, because console.log happens after Axios request:

async function getNbTicket(){
  let found = false;
  const { data } = await axios.get(link);
     data.data.map((element) => {
     if (element.id_ticket.toString() === nbTicket) found = true;
  });
  return found; 
}
about 4 years ago · Juan Pablo Isaza Relatório

0

This is normal behavior, because of the async and sync.

you have two options first one is to wrap your code inside a async function

const checkIfTicketIsFound = async () => {
  let found = false;
  const { data } = await axios.get(link);
  data.map((element) => {
    if (element.id_ticket.toString() === nbTicket) found = true;
  })
  console.log(found)
  return found
}

Or

you need to print inside the then chain

    let found = false;
    axios
       .get(link)
       .then((response) => {
          response.data.map((element) => {
             if (element.id_ticket.toString() === nbTicket) found = true;
          });
console.log(found);
       });
about 4 years ago · Juan Pablo Isaza Relatório
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