【问题标题】:Socket.io async/await for .on()Socket.io 异步/等待 .on()
【发布时间】:2021-02-01 23:36:07
【问题描述】:

我正在构建一个 socket.io Node JS 应用程序,我的 socket.io 服务器将监听来自许多 socket.io 客户端的数据,我需要尽快通过我的 socket.io 服务器将数据保存到 API并认为 async/await 是最好的前进方式。

现在,我的 .on('connection') 中有一个函数,但有没有办法可以将其设为异步函数,而不是在其中包含嵌套函数?

io.use((socket, next)  => {

  if (!socket.handshake.query || !socket.handshake.query.token) {
    console.log('Authentication Error 1')
    return
  }

  jwt.verify(socket.handshake.query.token, process.env.AGENT_SIGNING_SECRET, (err, decoded) => {
    if (err) {
      console.log('Authentication Error 2')
      return
    }
    socket.decoded = decoded
    next()
  })

}).on('connection', socket => {
  socket.on('agent-performance', data => {
    async function savePerformance () {
      const saved = await db.saveToDb('http://127.0.0.1:8000/api/profiler/save', data)
      console.log(saved)
    }
    savePerformance()
  })
})

【问题讨论】:

    标签: node.js sockets


    【解决方案1】:

    有点,但如果可能有多个 agent-performance 事件,您可能希望保留当前代码。您可以修改以下内容,但它会很混乱且可读性较差。事件发射器仍然存在是有原因的,它们并没有因为 Promise 的引入而过时。如果它是您所追求的性能,那么您当前的代码可能会更快,更能抵抗背压并且更容易错误处理。


    events.on 是一个实用函数,它接受一个事件发射器(如socket)并返回一个产生承诺的迭代器。您可以通过for await of 等待。

    events.once 是一个实用函数,它接受一个事件发射器(如socket)并返回一个在执行指定事件时解析的承诺。

    const { on, once } = require('events');
    
    (async function() {
      // This is an iterator that can emit infinite number of times.
      const iterator = on(io, 'connection');
      // Yield a promise, await it, run what is between `{ }` and repeat.
      for await (const socket of iterator) {
        const data = await once(socket, 'agent-performance');
        const saved = await db.saveToDb(/* etc */);
      }
    
    })();
    

    顾名思义,on 类似于socket.ononce 类似于socket.once。在上面的例子中:

    • 已连接用户 1,第一个代理性能事件:OK
    • 已连接用户 1,第二个代理性能事件:未处理,没有更多事件处理程序,因为 once 已“用完”。
    • 已连接用户 2,第一个代理性能事件:OK

    on 的文档有一个关于使用 for await (x of on(...)) 时并发性的说明,但我不知道这是否会成为您的用例中的问题。

        // The execution of this inner block is synchronous and it
       // processes one event at a time (even with await). Do not use
       // if concurrent execution is required.
    

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 1970-01-01
      • 2023-03-12
      • 2016-07-07
      • 2016-03-25
      • 2017-10-09
      • 2021-10-22
      相关资源
      最近更新 更多