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

187
Vistas
How to handle all WebSocket errors without a race?

When I run code

var ws = new WebSocket("wss://mydomain.example/socket/service");
ws.addEventListener("error", function (error)
{
  console.error("Got error=", error);
});

Is it possible that the WebSocket connection fails (emit error) before I can attach the event listener for the error event?

Looking at the documentation https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket I cannot see this detail documented anywhere.

According to the WHATWG spec it seems that the constructor should run the request in parallel – is there a guarantee that I can attach the error listener before any possible errors can raise?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The WebSocket constructor is run without synchronization of any kind and the connection may indeed encounter an error before the line with ws.addEventListener("error", ...); is executed! However, this is not a problem because the spec also says that in case of error, the actual error event is fired as a part of steps that must be queued as a task. In practice, this means that logically the WebSocket constructor is required to behave as if it would run an anonymous function with zero timeout which fires the error event.

So the actual error can happen before the JS code can attach the event listener but all the events (open, close, error, message) can only be fired delayed after the event loop is executed next time so the above code will always have to time attach the event handlers before the events can be fired.

See https://github.com/whatwg/websockets/issues/13#issuecomment-1039442142 for details.

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