我应该如何在 Promise 中初始化 WS 并在其外部使用它?

How should i initialize the WS in a Promise and use it outside of it?

我正在编写一个基于 WebSocket 调用的 JS 页面,首先我需要确保 WS 已启动并且它的状态已连接,否则我需要提示用户尝试重新连接。

然后用户将能够通过按一些按钮和其他东西与 WS 服务器通信。

所以我会知道哪种方式是初始化 WebSocket 并在单击按钮和其他方法时使用来自它的推送消息的最佳方式。

现在我的代码如下所示:

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
  });

我是否应该将所有使用 websocket 的点击方法放在 promise 中?

在 promise 中初始化 var 但在 promise 之外使用它是一种不好的做法吗?

Should i put all my click methods which uses websocket inside promise?

如果你的意思是在承诺履行处理程序中,那么:也许吧。您至少可以采用两种方法:

  1. 在 websocket 可用之前不要连接你的处理程序,或者

  2. 在您的处理程序中,允许 websocket 尚不可用的可能性,可能是通过保存承诺并每次使用 .then(或 await) .

这两种方法都是有效的,这取决于您的整体结构以及您的偏好。

#1 可能看起来像这样:

// 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 可能看起来像这样:

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
        });
});

Is it a bad practise to initialize the var in promise but use it outside of it?

不一定,但它经常表明你的整体结构有问题,所以这是一个聪明的问题,只要你想到你想做。 (也就是说,“我真的需要这样做吗?”)