【问题标题】:Socket.io - UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'emit' of undefinedSocket.io - UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“发出”
【发布时间】:2020-08-15 14:22:21
【问题描述】:

这是我写的:

io.sockets.connected[socketId].emit() // I'm sure `socketId` exists and connected.

但是出现错误:

(node:2416) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'emit' of undefined
    at ~/transmister/transmister-server-and-web/server.js:71:60
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:2416) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 5)

我的 Socket.io 版本是"socket.io": "^2.3.0"

此 API 是否已弃用?还是我的代码有问题?

【问题讨论】:

  • socketId 可能存在,但 io.sockets.connected[socketId] 不存在。
  • 我认为最好的方法是将任何套接字存储在connect 事件上并在disconnect 上删除它。顺便说一句,io.sockets.sockets[socketId] 有效吗?
  • @Namysh MrWillCom/labs/tree/master/socket.io-specific-msgs ,我最近测试过。
  • 而不是:sockets.push(socket.id) 然后io.sockets.connected[socket.id].emit('event', 'message');,尝试sockets[socket.id] = socket; 然后sockets[socket.id].emit('event', 'message');
  • @Namysh 演示是我实现它的方式,它有效,但它不起作用here,你能帮我找到问题吗?这里是README

标签: javascript node.js socket.io


【解决方案1】:

我发现我的数据库有问题,而不是 socket.io。现在已经修复了。

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 2021-05-20
    • 2021-04-18
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2021-05-18
    • 2021-01-15
    相关资源
    最近更新 更多