【问题标题】:How to return websocket message in functions?如何在函数中返回 websocket 消息?
【发布时间】:2020-07-17 07:12:31
【问题描述】:

我正在尝试创建一个从 WebSocket 服务器返回传入信息的函数。
我希望它在完成后在主文件中看起来像这样:

const getMessage = require('./getMessage.js');

let message = getMessage();
console.log(message);

现在我的问题是我不知道如何从事件监听器返回传入的消息

websocket.on('message', function incoming(reply) {

});

我的 getMessage.js 文件如下所示:

const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost');

module.exports = function getMessage() {
  let msg;
  ws.on('message', function incoming(reply) {
    msg = reply;
  });
  return msg;
}

但不是返回传入的消息,而是返回未定义的。如何在一个函数中获取 Websocket 服务器的传入消息?



index.js 的当前代码:

const api = require('./api.js');

let message = api();
console.log(messag); 

api.js 的当前代码:

const WebSocket = require('ws');

const ws = new WebSocket('ws://localhost');

let api = (function(msg) {
  console.log(msg);
  return msg;
});

    ws.on('message', function msg(reply) {
        api(reply);
    });

如果我运行它记录的程序:

未定义
未定义
你好

【问题讨论】:

    标签: node.js websocket node-modules


    【解决方案1】:

    您不能调用像 api 这样的函数来从 websocket 获取消息。 Websockets 本质上是异步的,所以你的incoming() 应该调用另一个函数,或者设置变量。

    也许可以尝试添加一个可以接收消息的回调函数。

    const WebSocket = require('ws');
    
    const ws = new WebSocket('ws://localhost');
    
    module.exports = function api(onMessageReceived) {
        if (typeof onMessageReceived !== 'function') {
            throw new Error('onMessageReceived must be a callback function');
        }
    
        ws.on('message', function(reply){
            onMessageReceived(reply);
        });
    };
    

    编辑:

    您不想将api 函数包装在括号中,并且不需要将其作为变量。尝试更多类似的东西:

    function api(msg) {
        console.log(msg);
    
        // "return"ing a value doesn't do anything, it is unneeded. 
    }
    
    ws.on('message', function msg(reply) {
        if (reply) {
            api(reply);
        }
    });
    

    【讨论】:

    • 遗憾的是它不起作用。每次都会抛出错误
    • 什么意思?我完全尝试了您建议的代码。
    • 当你调用你的api()时,你需要传递一个回调函数,像这样:api(function(msg) {console.log(msg);})或者更好的是api(myCallbackFunction)
    • 感谢您的帮助。只有一个新问题。现在程序记录了两次。脚本第一次记录 undefined 第二次记录消息。当我返回值时,它只返回 undefined。
    • 我不明白你想说什么。如果你能展示你当前的代码会更有帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多