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

185
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
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