Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
¿Cómo debo inicializar el WS en una promesa y usarlo fuera de él?

Estoy escribiendo una página JS basada en llamadas de WebSocket, en primer lugar, debo asegurarme de que el WS esté activo y que su estado esté conectado; de lo contrario, debo pedirle al usuario que intente volver a conectarse.

Luego, el usuario podrá comunicarse con WS Server presionando algunos botones y otras cosas.

Por lo tanto, sabría cuál sería la mejor manera de inicializar el WebSocket y usar mensajes de inserción al hacer clic en los botones y otros métodos.

Por ahora mi código se ve así:

 var websocket = null; document.getElementById("btnAnnullaStampa").addEventListener("click", () => { websocket.send(`<LOGIN><COD>${codope}</COD><PSW>${password}</PSW></LOGIN>`); }); function connect() { return new Promise(function (resolve, reject) { websocket = new WebSocket("ws://localhost:8080"); websocket.onopen = function () { resolve(websocket); }; websocket.onerror = function () { reject(); }; }); } connect(websocket) .then(function (server) { server.onmessage = (e) => { // DOING STUFF WITH WS MESSAGES } }) .catch(function (err) { // HERE I FIRE AN ERROR MODAL });

¿Debo poner todos mis métodos de clic que usan websocket dentro de la promesa?

¿Es una mala práctica inicializar la var en promesa pero usarla fuera de ella?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

¿Debo poner todos mis métodos de clic que usan websocket dentro de la promesa?

Si te refieres al interior de un controlador de cumplimiento de promesas, entonces: tal vez. Hay al menos dos enfoques que puede tomar aquí:

  1. No conecte sus controladores hasta que el websocket esté disponible, o

  2. En sus controladores, permita la posibilidad de que el websocket aún no esté disponible, probablemente guardando la promesa y usando await (o .then ) cada vez.

Cualquiera de los dos es un enfoque válido, depende de su estructura general y probablemente de su preferencia.

# 1 podría ser algo como esto:

 // Disable `btnAnnullaStampa` or don't show it at all to start with function connect() { return new Promise(function(resolve, reject) { const websocket = new WebSocket("ws://localhost:8080"); websocket.onopen = function() { resolve(websocket); }; websocket.onerror = function() { // You probably want to pass on any error you receive. // You might want to change this to just: // `websocket.onerror = reject;` reject(); }; }); } connect() .then(function(websocket) { websocket.onmessage = (e) => { // DOING STUFF WITH WS MESSAGES }; // Now, enable or show `btnAnnullaStampa` and hook it document.getElementById("btnAnnullaStampa").addEventListener("click", () => { websocket.send(`<LOGIN><COD>${codope}</COD><PSW>${password}</PSW></LOGIN>`); }); }) .catch(function(err) { // HERE I FIRE AN ERROR MODAL });

# 2 podría ser algo como esto:

 function connect() { return new Promise(function(resolve, reject) { const websocket = new WebSocket("ws://localhost:8080"); websocket.onopen = function() { resolve(websocket); }; websocket.onerror = function() { reject(); }; }); } const wsPromise = connect(); wsPromise .then(function(websocket) { websocket.onmessage = (e) => { // DOING STUFF WITH WS MESSAGES }; }) .catch(function(err) { // HERE I FIRE AN ERROR MODAL }); document.getElementById("btnAnnullaStampa").addEventListener("click", () => { wsPromise .then(ws => { // If this returns a promise, return that promise from this handler // by adding `return` at the beginning ws.send(`<LOGIN><COD>${codope}</COD><PSW>${password}</PSW></LOGIN>`); }) .catch(() => { // Show error about message not being sent }); });

¿Es una mala práctica inicializar la var en promesa pero usarla fuera de ella?

No necesariamente , pero a menudo indica un problema con su estructura general, por lo que es una pregunta inteligente para hacer cada vez que crea que quiere hacerlo. (Es decir, "¿Realmente necesito hacerlo de esta manera?")

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!