节点. js、mysql和socket.io

siv3szwd  于 2022-12-03  发布在  Mysql
关注(0)|答案(1)|浏览(127)

我是socket.io的新手。我遇到了一个问题。我如何在不重置node.js服务器的情况下显示数据库表中的实时数据。我在10秒内在表中有一个新数据。
我尝试了一些教程,但仍然有一个问题。

ljo96ir5

ljo96ir51#

您需要使用类似于以下内容的内容:

const sendDataCycle = async() => {
  try {
    const data = await getData() // get data from DB
    io.send(data) // send by socket.io
    setTimeout(() => {
      sendDataCycle() // send again after 10 s
    }, 10000)
  } catch (err) {
    setTimeout(() => {
      sendDataCycle() // if error - send again after 20 s or else
    }, 20000)
  }
}

sendDataCycle() // run cycle

请不要使用setInterval函数。

相关问题