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

186
Visualizações
Websocket response data undefined in global variable

I would like to use the global variable data and assign the WebSocket response data to it but inside the function the data is displayed outside is undefined.

How can I solve this?

var data;

client.onopen = () => {
  console.log("WebSocket Client Connected!");
};

client.onmessage = (message) => {
  data = message.data;
  console.log(data); // json data in console
};

client.onerror = function () {
  console.log("Connection Error");
};

console.log(data); // undefined
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It is because the last console.log happens before the socket event happens that why the variable is undefined if you want to see the variable you need to call it by function after the socket event emited

about 4 years ago · Juan Pablo Isaza Relatório

0

The data variable is not defined at the time when console.log executes, you tried to log the variable to the console before your client received the message.

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